Manny
Manny

Reputation: 79

how can I count data from foreign key field in Django template?

models.py:

class Region(models.Model):
    city = models.CharField(max_length=64)

class Properties(models.Model):
    title = models.CharField(max_length=200)
    Region = models.ForeignKey(Region, related_name='Region', on_delete=models.Cascade)

how can i count all properties which have the same region ?

Upvotes: 0

Views: 95

Answers (1)

Sorin Burghiu
Sorin Burghiu

Reputation: 779

you can do a filter query followed by a count. For example:

london_properties_count = Properties.objects.filter(region__city='london').count()

Conventionally, you want to have fields on a model in lowercase, so instead of Region = models.ForeignKey(..), have region = models.ForeignKey(..)

Upvotes: 1

Related Questions