Eric
Eric

Reputation: 601

Sum and Count in nested foreign key relationship?

I have the following models:

class Building():

class Floor():
    building = models.ForeignKey("Building")

class Suite():
    floor = models.ForeignKey("Floor")
    area = models.FloatField()
    available = models.BooleanField()

In the serializer for Building, across the whole building, I would like to

I'm pretty sure that I can sum area of a list of suites like this:

models.Suite.objects.filter(Q(available=True)).aggregate(Sum('area'))

I don't know how to nest this so that I can query the data for the entire building...

Upvotes: 4

Views: 1362

Answers (1)

Jahongir Rahmonov
Jahongir Rahmonov

Reputation: 13753

I think you can do these:

To count available suites in a building:

Suite.objects.filter(floor__building=building, available=True).count()

To sum available suites' areas:

Suite.objects.filter(floor__building=building, available=True).aggregate(Sum('area'))

Hope it helps!

Upvotes: 5

Related Questions