how to count all distinct records in many-to-many relations in django ORM?
Posted
by marduk-pl
on Stack Overflow
See other posts from Stack Overflow
or by marduk-pl
Published on 2010-03-25T11:12:24Z
Indexed on
2010/03/25
13:23 UTC
Read the original article
Hit count: 330
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?
© Stack Overflow or respective owner