Django order_by() filter with distinct()

pkdkk picture pkdkk · Dec 14, 2013 · Viewed 31.7k times · Source

How can I make an order_by like this ....

p = Product.objects.filter(vendornumber='403516006')\
                   .order_by('-created').distinct('vendor__name')

The problem is that I have multiple vendors with the same name, and I only want the latest product by the vendor ..

Hope it makes sense?

I got this DB error:

SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON ("search_vendor"."name") "search_product"...

Answer

janos picture janos · Dec 14, 2013

Based on your error message and this other question, it seems to me this would fix it:

p = Product.objects.filter(vendornumber='403516006')\
               .order_by('vendor__name', '-created').distinct('vendor__name')

That is, it seems that the DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s). So by making the column you use in distinct as the first column in the order_by, I think it should work.