Django聚合过滤查询

时间:2014-12-18 15:27:59

标签: django django-models django-orm

假设我有这两个模型:

class User(models.model):
    username = models.CharField(max_length=255)

class Item(models.model):
    user = models.ForeignKey( User )
    enabled = models.BooleanField()
    price = models.IntegerField()

我想创建一个最佳查询并获得:至少有10个启用的前10位用户 项目和总项目的最高平均价格(按最佳平均排序)

换句话说,我正试图创建一个前10名"排行榜"在我的网站上为拥有平均价格最高的商品的用户,但是有些商品可能被禁用并且仍然存在于我的数据库中,我试图在我的ORM查询中删除它们但是无法找到一个好方法

此操作每5分钟左右运行一次,在生成页面时不会运行。

1 个答案:

答案 0 :(得分:2)

我现在无法测试,但我认为这应该有效:

topusers = User.objects.prefetch_related(
                'item_set'
            ).filter(
                item_set__enabled=True
            ).annotate(
                item_count=models.Count('item_set'),
                avg_price=models.Avg('item_set__price')
            ).filter(
                item_count__gte=10
            ).order_by('-avg_price').all()