Last active
June 29, 2016 16:19
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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