Damian
Damian

Reputation: 120

list row of foreign key model

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

Answers (3)

suhailvs
suhailvs

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

Rohan
Rohan

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

Burhan Khalid
Burhan Khalid

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

Related Questions