Reputation: 18745
I have these models:
class Product(Model):
...
class Scanning(Model):
product = ForeignKey(..)
datetime = DateTimeField(...)
...
I'm trying to get one scanning for each product where the scanning is a latest one from product.scanning.all()
set.
s1 = (product1,01.01.1000)
s2 = (product2,01.01.1200)
s3 = (product1,01.01.1900)
s4 = (product2,01.01.1988)
s5 = (product3,01.01.2015)
s6 = (product3,01.01.1970)
would return <s4,s3,s5>
Scanning.objects.filter(product__user=u,product__active=True).distinct('product_id').order_by('datetime')
Raises exception:
ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON ("productapp_scanning"."product_id") "pro... ^
How to make it work?
Upvotes: 0
Views: 282
Reputation: 6106
With postgres, you cannot do distinct
on a field, unless it's also what you sort by:
Scanning.objects.filter(product__user=u,product__active=True).distinct('product_id').order_by('product_id', 'datetime')
If that's not good enough, one solution is to make a double query like this:
q1 = Scanning.objects.filter(product__user=u,product__active=True).values('product_id').distinct().annotate(x=Max('id'))
q2 = Scanning.objects.filter(id__in=[i["x"] for i in q1])
Upvotes: 1