Reputation: 120
i have a question with the next model:
class Product(models.Model):
id_product = models.AutoField(primary_key=True)
title = models.CharField()
def __unicode__(self):
return self.title
class Orders(models.Model):
id_order = models.AutoField(primary_key=True)
product = models.ForeignKey(Product)
description = models.CharField(max_length=150, null=True, blank=True)
date = models.DateTimeField()
def __unicode__(self):
return self.description
How can I list all product and the last order of each product ?
Thanks.
Upvotes: 0
Views: 74
Reputation: 21680
you can select all products and the last order of each product ?
for i in Products.objects.all():
i,Orders.objects.filter(product=i).latest('date')
Upvotes: 0
Reputation: 53326
You can do this
>>> for product in Product.objects.all():
print product, product.orders_set.latest('date')
For each product, you can access set of orders as product.orders_set
which is relationship manager using which you can do queries.
Upvotes: 1
Reputation: 174624
You should name your classes in the singular, Order as opposed to Orders.
If you are using postgresql, you can do this:
Orders.objects.order_by('-date').distinct(product)
Otherwise:
[(p,p.orders_set.latest('date')) for p in Product.objects.all()]
Upvotes: 0