Hans de Jong
Hans de Jong

Reputation: 2078

Count the related objects of a related object

I got 3 models:

Upgrade keeps track of a building that is being upgraded.

class Town(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=63)


class Building(models.Model):
    template = models.ForeignKey(BuildingTemplate, related_name='building_template')
    town = models.ForeignKey(Town)
    level = models.IntegerField()


class Upgrade(models.Model):    
    building = models.ForeignKey(Building)
    timer = models.DateTimeField()

Now I want to count the amount of buildings that a town has in upgrade. Now I guess I could do this with some for loops, but I wondered if there wasn't a better way by using the Django API.

Upvotes: 0

Views: 63

Answers (2)

Renoc
Renoc

Reputation: 439

The previous answer will count the same building multiple times if they have multiple upgrades. Use this instead:

count = Building.objects.filter(town=town).exclude(upgrade=None).count()

Upvotes: 1

Hans de Jong
Hans de Jong

Reputation: 2078

I found out with the linked documentation that this works for me:

count = Upgrade.objects.filter(building__town=building.town).count()

Upvotes: 0

Related Questions