[Django]-Django model manytomany field count occurrence

2👍

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.

Leave a comment