Skip to content

Instantly share code, notes, and snippets.

@karolyi
Last active June 29, 2016 16:19
Show Gist options
  • Save karolyi/223dc88213579414676dc1f224bab583 to your computer and use it in GitHub Desktop.
Save karolyi/223dc88213579414676dc1f224bab583 to your computer and use it in GitHub Desktop.
Django selecting newest values on a field by 'grouping' on the same table
# We have a Django `Updates` model with `product`, `date`, `version` fields.
# We want to fetch the newest versions of products without executing many queries, in a Django way.
from django.db.models import CharField, Value as V
from django.db.models.functions import Concat
a = Updates.objects.values('product_id').annotate(cc=Concat('product_id', V('-'), Max('date'), output_field=CharField())).values('cc')
b = Updates.objects.annotate(cc=Concat('product_id', V('-'), 'date', output_field=CharField())).filter(cc__in=a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment