Django generate group by different than id

狂风中的少年 提交于 2019-12-12 21:16:14

问题


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

output sql

SELECT
  "user"."product_id"
  COUNT("user"."product_id") AS "product_count"
FROM "user"
WHERE "user"."age" > 18
GROUP BY "user"."id";

desired sql:

SELECT
  "user"."product_id"
  COUNT("user"."product_id") AS "product_count"
FROM "user"
WHERE "user"."age" > 18
GROUP BY "user"."product_id";

回答1:


I don't think that makes any sense. What you want is probably this:

Product.objects.annotate(user_count=Count('user'))


来源:https://stackoverflow.com/questions/56573615/django-generate-group-by-different-than-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!