Jamgreen
Jamgreen

Reputation: 11039

Nested annotation in Django

I have three models

class ModelA(models.Model):
    name = CharField(max_length=100)

class ModelB(models.Model):
    modela = ForeignKey(ModelA)

class ModelC(models.Model):
    modelb = ForeignKey(ModelB)

How can I print all ModelA objects with the number of 'associated' ModelC objects?

Output:

name, num model c objects
======
Some name, 17
Another name, 3

I've tried making a queryset from ModelA like this:

ModelA.objects.all().values('name').annotate('modelb_set__modela_set')

but it does not work.

Upvotes: 2

Views: 1824

Answers (1)

klasske
klasske

Reputation: 2174

You should use Count here and reference ModelC in your query

from django.db.models import Count
ModelA.objects.all().values('name').annotate(num_model_c_objects=Count('modelb__modelc'))

Upvotes: 1

Related Questions