agua95
agua95

Reputation: 67

Django Model Occurrence Count

I'm fairly new to Django and I'm in need of assistance with my models.

class Region(models.Model):
    region_name = models.CharField(max_length=10)
    def __str__(self):
        return self.region_name

class Property(models.Model):
    prop_name = models.CharField(max_length=200)
    region_name = models.ForeignKey(Region, on_delete=models.CASCADE, verbose_name="Region")
    prop_code = models.IntegerField(default=0, verbose_name="Property")
    def __str__(self):
        return self.prop_name

class Sale(models.Model):
    prop_name = models.ForeignKey(Property, on_delete=models.CASCADE)
    employee = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Person")
    prop_state = models.CharField(null=True, max_length=5, choices=[('new','New'),('used','Used')])
    date = models.DateField('Sale Date')
    def __str__(self):
        return '%s : %s %s - %s' % (self.prop_name.prop_name, self.employee, self.date, self.prop_state)

Here are my models. Property inherits from Region and Sale inherits from property. What I want to do is count the number of sales in a region and the number of sales on a specific property. However I do not know which would be the best way to approach this. I've tried using a lambda as a model field that uses the count() function but I wasn't able to see much success with that. Please let me know if you have any suggestions.

Upvotes: 3

Views: 120

Answers (2)

Iceandele
Iceandele

Reputation: 660

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

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476739

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.

Upvotes: 2

Related Questions