[Fixed]-Django/Postgres: Choose from DISTINCT ON sets

1👍

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])
👤NS0

Leave a comment