Django generate group by different than id

Viewed 1076

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 Answers

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

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