Django model manytomany field count occurrence

Viewed 95

models.py

class Region(models.Model):
    name = models.CharField(blank=False, unique=True)
    count = models.IntegerField(blank=True, null=True) # This should be the occurrence count in ETF

class ETF(models.Model):
    ticker = models.CharField() 
    region = models.ManyToManyField(Region, blank=True)

Example: If there is 100 ETF objects in ETF model have U.S.A. as region, then count field in U.S.A. object in Region model should be 100.

How do I automatically update the count field in Region Model everytime there are changes in the database? Sorry if there is duplicate question,

I just can't find the keywords to search for the solution.

1 Answers

You do not need to count the number of ETFs for a Region, you can calculate that when necessary with .annotate(…) [Django-doc]:

from django.db.models import Count

Region.objects.annotate(
    count_etf=Count('etf')
)

The Regions that arise from this queryset will have an extra attribute .count_etf that contains the number of related ETF objects for that Region.

If an ETF is linked to multiple Regions, than all these regions will count that as one.

Related