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";
Product.objects.annotate(user_count=Count('user')).values('id').order_by('id')
– Namtar