我要计算同一产品的用户数量
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";
答案 0 :(得分:2)
我认为这没有任何意义。您想要的可能是这样:
Product.objects.annotate(user_count=Count('user'))