本文介绍了Django,使用其他表格中的数据进行注释和排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,有些用户请求捐赠这些项目的项目和用户。我想获取最多捐款的所有用户。

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.

这些是我的模型:

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)

更具体地说,我想以最完成的捐款(其中 item_request.completed = True)获取前5名捐助者。。我可以用一个查询来执行此操作吗?

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])

您应该可以命​​名您的 Donation.user.related_name 捐赠

You should probably name your Donation.user.related_name donation too.

然后它将是

(User.objects
       .filter(donation__item_request__completed=True)
       .annotate(c=Count('donation'))
       .order_by('-c')[:5])

这篇关于Django,使用其他表格中的数据进行注释和排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 01:31