[Django]-Django Model Occurrence Count

2๐Ÿ‘

โœ…

If you already have your Property/Region objects, something like this should work

sales_per_property = Sale.objects.filter(prop_name=property).count()
sales_per_region = Sale.objects.filter(prop_name__region_name=region).count()

Edit:

Seeing that you tried to add a lambda function to the model field, this may be more what you are looking for.

class Region(models.Model):
    ...
    @property
    def sales(self):
        return Sale.objects.filter(prop_name__region_name=self).count()

and similarly for Property. Simply access the property using region.sales

๐Ÿ‘คIceandele

2๐Ÿ‘

You can annotate your querysets for Region and Property. For example:

from django.db.models import Count

regions = Region.objects.annotate(sales=Count('property__sale'))
properties = Property.objects.annotate(sales=Count('sale'))

The Regions/Propertys that arise from these querysets will have an extra attribute .sales that contains the number of related Sale objects.

Leave a comment