[Answer]-List row of foreign key model

0👍

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')

1👍

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.

👤Rohan

0👍

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()]

Leave a comment