Django Query That Get Most Recent Objects From Different Categories

Starting from Django 1.11 and thanks to Subquery and OuterRef, we can finally build a latest-per-group query using the ORM. hottest_cakes = Cake.objects.filter( baked_at=Subquery( (Cake.objects .filter(bakery=OuterRef(‘bakery’)) .values(‘bakery’) .annotate(last_bake=Max(‘baked_at’)) .values(‘last_bake’)[:1] ) ) ) #BONUS, we can now use this for prefetch_related() bakeries = Bakery.objects.all().prefetch_related( Prefetch(‘cake_set’, queryset=hottest_cakes, to_attr=”hottest_cakes” ) ) #usage for bakery in bakeries: print ‘Bakery … Read more

How to annotate Count with a condition in a Django queryset

For django >= 1.8 Use Conditional Aggregation: from django.db.models import Count, Case, When, IntegerField Article.objects.annotate( numviews=Count(Case( When(readership__what_time__lt=treshold, then=1), output_field=IntegerField(), )) ) Explanation: normal query through your articles will be annotated with numviews field. That field will be constructed as a CASE/WHEN expression, wrapped by Count, that will return 1 for readership matching criteria and NULL … Read more

How to get primary keys of objects created using django bulk_create

2016 Since Django 1.10 – it’s now supported (on Postgres only) here is a link to the doc. >>> list_of_objects = Entry.objects.bulk_create([ … Entry(headline=”Django 2.0 Released”), … Entry(headline=”Django 2.1 Announced”), … Entry(headline=”Breaking: Django is awesome”) … ]) >>> list_of_objects[0].id 1 From the change log: Changed in Django 1.10: Support for setting primary keys on objects … Read more

Why does django’s prefetch_related() only work with all() and not filter()?

In Django 1.6 and earlier, it is not possible to avoid the extra queries. The prefetch_related call effectively caches the results of a.photoset.all() for every album in the queryset. However, a.photoset.filter(format=1) is a different queryset, so you will generate an extra query for every album. This is explained in the prefetch_related docs. The filter(format=1) is … Read more