Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, annotation and ordering using data from other table

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?

like image 529
xpanta Avatar asked Feb 01 '26 04:02

xpanta


1 Answers

(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])
like image 119
Pavel Anossov Avatar answered Feb 02 '26 17:02

Pavel Anossov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!