Django novice question :)
I have the following models - each review is for a product, and each product has a department:
class Department(models.Mod
The Docs for aggregation https://docs.djangoproject.com/en/dev/topics/db/aggregation/#cheat-sheet
There probably is a way to use aggregate or annotate, but I prefer this:
departments = Department.objects.all()
for dept in departments :
# Get the number of reviewed products for a given range and department
num_products = dept.product_set.filter(review__time__range=["2012-01-01", "2012-01-08"]).count()
if you absolutely need it as a function of the model:
class Department(models.Model) :
...
def num_products(self, start_date, end_date) :
return self.product_set.filter(review__time__range=[start_date, end_date]).count()
I think that if you were to do a raw query (something like this)
sql = """SELECT COUNT(Product.*) as num_products, Department.*
FROM Department
LEFT OUTER JOIN Product ON Product.department = Department.id
LEFT OUTER JOIN Review ON Product.id = Review.product
WHERE Review.time BETWEEN "2012-01-01" AND "2012-01-08"
GROUP BY Department.id"""
Department.objects.raw(sql)
and then num_products will be an attribute on every Dept instance in the results.
you may need to play with the field + table names a little