Django, annotation and ordering using data from other table -


in app there users request items , users donate items. fetch users made donations.

these models:

class itemrequest(models.model):     item_type = models.foreignkey(itemtype)     description = models.charfield(max_length=1024, default='', blank=true)     quantity = models.integerfield()     user = models.foreignkey(user)     completed = models.booleanfield(default=false)     completed_dt = models.datetimefield()   class donation(models.model):     item_request = models.foreignkey(itemrequest, related_name='donation')     user = models.foreignkey(user, related_name='donor')     quantity_offered = models.integerfield(default=0)     quantity_accepted = models.integerfield(default=0) 

more specifically, fetch top-5 donors "completed" donations (where item_request.completed=true). can 1 query?

(user.objects        .filter(donor__item_request__completed=true)        .annotate(c=count('donor'))        .order_by('-c')[:5]) 

you should name donation.user.related_name donation too.

then be

(user.objects        .filter(donation__item_request__completed=true)        .annotate(c=count('donation'))        .order_by('-c')[:5]) 

Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -