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

Optimize GROUP BY query to retrieve latest row per user

For best read performance you need a multicolumn index: CREATE INDEX log_combo_idx ON log (user_id, log_date DESC NULLS LAST); To make index only scans possible, add the otherwise not needed column payload in a covering index with the INCLUDE clause (Postgres 11 or later): CREATE INDEX log_combo_covering_idx ON log (user_id, log_date DESC NULLS LAST) INCLUDE … Read more

Select info from table where row has max date

SELECT group,MAX(date) as max_date FROM table WHERE checks>0 GROUP BY group That works to get the max date..join it back to your data to get the other columns: Select group,max_date,checks from table t inner join (SELECT group,MAX(date) as max_date FROM table WHERE checks>0 GROUP BY group)a on a.group = t.group and a.max_date = date Inner … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)