Django通过不同于id生成分组 [英] Django generate group by different than id
本文介绍了Django通过不同于id生成分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要计算同一产品的用户数量
I want to count amount of Users for same Product
models.py
class Product(models.Model):
pass
class User(models.Model):
product = models.ForeignKey(Product)
age = models.IntegerField(blank=True, null=True)
User.objects.filter(age__gt=18).annotate(product_count=Count('product_id'))
输出sql
SELECT
"user"."product_id"
COUNT("user"."product_id") AS "product_count"
FROM "user"
WHERE "user"."age" > 18
GROUP BY "user"."id";
所需的SQL :
SELECT
"user"."product_id"
COUNT("user"."product_id") AS "product_count"
FROM "user"
WHERE "user"."age" > 18
GROUP BY "user"."product_id";
推荐答案
我认为这没有任何意义。您想要的可能是这样的:
I don't think that makes any sense. What you want is probably this:
Product.objects.annotate(user_count=Count('user'))
这篇关于Django通过不同于id生成分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文