In my app there are users who request items and users who donate those items. I would like to fetch all users that made the most donations.
These are my 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, I would like to fetch the top-5 donors with the most "completed" donations (where item_request.completed=True). Can I do this with one query?
(User.objects
.filter(donor__item_request__completed=True)
.annotate(c=Count('donor'))
.order_by('-c')[:5])
You should probably name your Donation.user.related_name donation too.
Then it will be
(User.objects
.filter(donation__item_request__completed=True)
.annotate(c=Count('donation'))
.order_by('-c')[:5])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With