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 Region
s/Property
s that arise from these querysets will have an extra attribute .sales
that contains the number of related Sale
objects.
- [Django]-Is sqlite bundled into Django?
- [Django]-How to cast Django form to dict where keys are field id in template and values are initial values?
- [Django]-Django: how to map the results of a raw sql query to model instances in admin list view?
- [Django]-Django queries: Count number of objects with FK to model instance
Source:stackexchange.com