Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  • count 'available' suites
  • sum 'available' suites 'area' fields

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...

like image 439
Eric Avatar asked Sep 01 '25 10:09

Eric


1 Answers

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!

like image 185
Jahongir Rahmonov Avatar answered Sep 04 '25 05:09

Jahongir Rahmonov