问题
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