python - How to get latest record per user whilst filtering on another (annotate?) -


i have model baz. want list of latest baz (descending order) each user_bar, filtering on single user_foo.

class baz(models.model):     foo = models.foreignkey(user, db_index=true, related_name='user_foo')     bar = models.foreignkey(user, db_index=true, related_name='user_bar')     content = models.charfield(max_length=32)     created = models.datetimefield(db_index=true, auto_now_add=true) 

so example there baz records, , filter "tom":

id  foo     bar     content --  ---     ---     ------- 1   tom     dick    text 2   tom     harry   more text 3   dick    tom     more text  4   tom     dick    last text ever 

in case query return:

id  foo     bar     content --  ---     ---     ------- 4   tom     dick    last text ever 2   tom     harry   more text 

...assuming records created in order.

this records, there multiple records each user_bar (i want latest each user_bar):

baz.objects.filter(foo=request.user).order_by('-created') 

(update) tried this:

baz.objects.filter(foo=request.user).values('bar'). annotate(max('created')).order_by('-created') 

...but not contain fields:

'dict' object has no attribute 'content' 

this close want, not order records latest first because bar takes precedence in ordering:

baz.objects.filter(foo=request.user).order_by('bar',      '-created').distinct('bar') 

this job, seems overly complicated:

ids = baz.objects.filter(foo=request.user).order_by('bar',      '-created').distinct('bar').values_list('id') baz.objects.filter(id__in=ids).order_by('-created') 


Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -