I am very new to django and I'm making a project that tracks medications in our drug safe. Part of our daily activities is to check the amount of each drug in the safe and document each amount. In my model for the safe, I have a field "drug_name" that is a foreign key to a list of medications. I want to make a model form that auto populates each choice in the field and asks for the amount of the drug in the safe. Something like:
Drug Name 1
Amount:_________
Drug Name 2
Amount:_________
and so on.
Here is my model
class Safe(models.Model):
user = models.ForeignKey(User, on_delete=models.PROTECT)
date_created = models.DateTimeField(auto_now=True)
drug_name = models.ForeignKey('components.Drug', related_name='drug_remove', on_delete=models.PROTECT, default=0, limit_choices_to={'is_active': True})
amount_removed = models.IntegerField(blank=True, null=True)
amount_added = models.IntegerField(blank=True, null=True)
amount_in_safe = models.IntegerField(blank=True, null=True)
incident_number = models.CharField(max_length=20, default=0, blank=True)
patient_name = models.CharField(max_length=20, default=0, blank=True)
medic_unit = models.ForeignKey('components.MedicUnit', related_name='medic_unit', on_delete=models.PROTECT, blank=True, null=True)
free_text = models.CharField(max_length=1000, default=0, blank =True)
I'm not sure if I could submit all at once or if I would have to submit one drug at a time. Either way would work well as long as the user didn't have to manually select each medication. Thanks ahead of time for any help.
Related
class ChargeOverInvoice(models.Model):
id = models.CharField(db_column='Id', max_length=18, primary_key=True)
created_date = models.DateTimeField(db_column='CreatedDate', auto_now_add=True)
class ChargeOverTransaction(models.Model):
name = models.CharField(db_column='Name', max_length=80, verbose_name='Transaction #',
default=models.DEFAULTED_ON_CREATE, blank=True, null=True)
chargeover_invoice_id = models.CharField(db_column='ChargeOver_Invoice_ID__c', max_length=255)
customer = models.ForeignKey(Account, models.DO_NOTHING, db_column='Customer__c')
invoice = models.ForeignKey(ChargeOverInvoice, models.DO_NOTHING, db_column='ChargeOver_Invoice__c', blank=True,
null=True)
status = models.CharField(db_column='Status__c', max_length=255, verbose_name='Status')
created_date = models.DateTimeField(db_column='CreatedDate', verbose_name='Created Date')
I can get the result if it was about filtering within dates like this
ChargeOverTransaction.objects.filter(status='Failed (decline)', created_date__lte=now()-relativedelta(days=35)).values('customer', 'invoice', 'chargeover_invoice_id').annotate(total=Count('id')).filter(total__gte=5)
But not sure how can I get the latest 5 and add validation on them.
You can combine window function to find five latest transactions for the invoice.
And use django-cte to filter the result.
I'm writing the management interface for a competition, and have the following models:
class Heat(models.Model):
current_heat = models.IntegerField()
track = models.ForeignKey(Track, on_delete=models.PROTECT)
previous_heat = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True)
start_date = models.DateTimeField('Start Date', default=timezone.now)
end_date = models.DateTimeField('End Date', null=True, blank=True)
class Game(models.Model):
heat = models.ManyToManyField(Heat)
format = models.TextField(max_length=20, default="V")
player1 = models.ForeignKey(User, on_delete=models.PROTECT, related_name='player1')
player2 = models.ForeignKey(User, on_delete=models.PROTECT, related_name='player2')
winner = models.ForeignKey(User, on_delete=models.PROTECT, related_name='winner', null=True, blank=True)
Now I want to get the standings for a specific heat. In other words, I want to get all unique players in that heat, together with how many wins they got (thus where they are in Game.winner), and how many losses they got (thus where Game.winner is not that player but it is not Null, and they are in either Game.player1 or Game.player2.)
Ideally, this should then even be ordered by wins (descending), losses (ascending).
I've been looking through the aggregation docs from Django, but I don't see how to start since I need to get so many different things all combined.
I have two models which I want to join but they don't have any foreignkey
class Invoice(models.Model):
invoice_id = models.IntegerField(blank=True, null=True)
quotation_id = models.IntegerField(blank=True, null=True)
client_id = models.ForeignKey(tbl_customer, on_delete=models.CASCADE)
invoice_number = models.IntegerField(blank=True, null=True)
quotation_number = models.IntegerField(blank=True, null=True)
date = models.DateField(blank=True, null=True)
total_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)
total_tax = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)
document_type = models.CharField(max_length=50, default='', blank=True, null=True)
and
class Invoice_Description(models.Model):
invoice_id = models.IntegerField(blank=True, null=True)
client_id = models.ForeignKey(tbl_customer, on_delete=models.CASCADE)
quotation_id = models.IntegerField(blank=True, null=True)
item_id = models.ForeignKey(tbl_item, on_delete=models.CASCADE)
item_qty = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)
item_unit_price = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)
Invoice contains information about the invoice document, its total price, date, etc while Invoice_Description keeps the records of items added on that particular invoice, item price, total quantity, discount on each item, etc.
I want to display all the records in reports with respect to items like
ITEM NAME CUSTOMER NAME INV. NO. QTY DOCUMENT TYPE UNIT PRICE SALE PRICE
Item1 Client1 01 950.00 1000.00
I have all the columns available from Invoice_Description except for the INV. NO. and DOCUMENT TYPE which are in the Invoice model.
I don't want to use a ForeignKey in this case because these models are already in use in many places, changing the database will require changes everywhere.
my problem is just that I want to join two models in Django but without ForeignKey so that I may get Invoice No. and Document Type of the corresponding row.
Any ideas on how can I do this??
If all you want to do is retrieve an InvoiceDescription object that belongs to a given Invoice, you could do the following:
invoice = Invoice.objects.first()
try:
description = InvoiceDescription.objects.get(invoice_id=invoice.invoice_id)
except InvoiceDescription.DoesNotExist:
description = None
I am assuming that the field invoice_id refers to the invoice ID. Although you didn't declare it using models.ForeignKey, it still acts as a foreign key in this situation. You just have to do the lookup manually.
I have two tables Customer and Subscription in which Customer has the list of customers and Subscription contains the Customer and Packages.
In the customer list i want to show how many packages each customer has.
Subscription Model
class Subscription(models.Model):
client = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True, related_name="subscriptions")
package = models.ForeignKey(Package, on_delete=models.SET_NULL, blank=True, null=True)
valid_start_date = models.DateTimeField()
valid_end_date = models.DateTimeField()
usage_count = models.IntegerField(null=True)
status = models.CharField(max_length=20)
transaction = models.BigIntegerField(blank=True, null=True, default=0)
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
Customer Model
class Customer(AbstractBaseUser):
first_name = models.CharField(max_length=250, blank=True, null=True)
last_name = models.CharField(max_length=250, blank=True, null=True)
email = models.EmailField(unique=True, blank=True, null=True)
mobile_number = models.BigIntegerField(blank=True, null=True)
password = models.CharField(max_length=1000, blank=True, null=True)
gender = models.CharField(max_length=10, blank=True, null=True)
profile_picture = models.ImageField(upload_to="user_data/profile_picture", blank=True)
address = models.CharField(max_length=500, blank=True, null=True)
country = models.ForeignKey(Countries, on_delete=models.SET_NULL, blank=True, null=True)
state = models.ForeignKey(States, on_delete=models.SET_NULL, blank=True, null=True)
city = models.ForeignKey(Cities, on_delete=models.SET_NULL, blank=True, null=True)
pincode = models.IntegerField(blank=True, null=True)
number_of_logins = models.IntegerField(blank=True, null=True)
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
USERNAME_FIELD = "email"
Expected Result : I want to show the package field data from Subscription Model into the list of Customer model.
name - no. - emaiId- pakages_subbed
customer1 - mobile - email - package1,package2
customer2 - mobile - email - package4,package1
Actual Result : Only Customer field data
You need to use annotate in your queryset much as here
I think
query = Customer.objects.annotate(subscription_count=Count('subscriptions'))
ought to do it (with the count available as object.subscription_count for any object retrieved from this query)
This is just one database query, returning only Customer objects, whereas {{ customer.subscriptions.all|length }} will be a lot of them (and will probably also retrieve all the Subscription objects just to count them).
If you wanted greater access to the Subscription and Package objects you could do
Subscription.objects.all().order_by("client__id", "package__name")...
(I made up "package__name") which should get you the subscriptions grouped firstly by customer and then ordered by package name for each customer.
#models.py
class Orders(models.Model):
orderid = models.IntegerField(db_column='orderID', primary_key=True)
createdate = models.DateField(db_column='createDate', blank=True, null=True)
pickupdate = models.DateField(db_column='pickupDate', blank=True, null=True)
returndate = models.DateField(db_column='returnDate', blank=True, null=True)
pickupstore = models.ForeignKey(Branch, models.DO_NOTHING, db_column='pickupStore', blank=True, null=True,related_name = 'pickupstore')
returnstore = models.ForeignKey(Branch, models.DO_NOTHING, db_column='returnStore', blank=True, null=True,related_name = 'returnstore')
rentedvehicle = models.ForeignKey('Vehicles', models.DO_NOTHING, db_column='rentedVehicle', blank=True, null=True)
customer = models.ForeignKey(Customer, models.DO_NOTHING, db_column='customer', blank=True, null=True)
class Vehicles(models.Model):
vehicleid = models.IntegerField(db_column='vehicleID', primary_key=True)
make = models.CharField(max_length=45, blank=True, null=True)
model = models.CharField(max_length=45, blank=True, null=True)
series = models.CharField(max_length=45, blank=True, null=True)
Orders model have foreign key rentedvehicle which refers to Vehicles models
I have filtered the data based on the pickupstore state, e.g. The list of vehicles that are picked up from store in a particular state
Vehicles.objects.filter(orders__pickupstore__state = request.POST['state'])
I want to be able to filter the filtered data above so that I can get a list of vehicles that are picked up from store in a particular state WITH its latest entry in Orders models has returnstore__state == a particular state
So basically, I want to achieve this:
Vehicles.objects.filter(orders__pickupstore__state = request.POST['state']).filter(the latest entry returnstore state =request.POST['state'])
Many possible solutions. Optimal depends on your Django version (1.11 or higher?). Here's one possible solution:
from django.db.models import Max, F
Vehicles.objects.filter(orders__pickupstore__state = request.POST['state']).annotate(max_date=Max('orders__returndate')).filter(orders__return_date=F('max_date')).filter(orders__state = request.POST['state'])
What's happening here is that we're identifying the most recent return date, then filtering the orders to only include the most recent, then filtering the Vehicles on the state of that latest order.