how to count all distinct records in many-to-many relations in django ORM?
- by marduk-pl
hi, i have two models:
class Project(models.Model):
categories = models.ManyToManyField(Category)
class Category(models.Model):
name = models.CharField()
now, i make some queryset:
query = Project.objects.filter(id__in=[1,2,3,4])
and i like to get list of all distinct categories in this queryset with count of projects with refering to these categories - exactly i would like to get that results:
category1 - 10 projects
category2 - 5 projects
that is opposite to this query:
query2 = query.annotate(Count('categories'))
what return me:
project1 - 2categories
project2 - 7categories
how can i make it in django ORM?