tags:

views:

120

answers:

1

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?

A: 
Category.objects.filter(project__in=query).annotate(Count('project'))
Dmitry Shevchenko
yes, but i like to get only categories from this specific queryset (Project.objects.filter(id__in=[1,2,3,4])), not from all categories in database
updated my answer
Dmitry Shevchenko