Django novice question :)
I have the following models - each review is for a product, and each product has a department:
class Department(models.Mod
I've had to do a couple of similar queries in the last few days and the easiest way it to use the extra queryset function to annotate each object in your queryset with a filtered count of the products:
start = .. # need to be formatted correctly
end = ...
departments = Departments.objects.all().extra(select = {
'product_count' : """ SELECT COUNT(*) FROM appname_department
JOIN appname_product
ON appname_product.dept_id = appname_department.id
JOIN appname_review
ON appname_review.product_id = appname_product.id
WHERE appname_review.time BETWEEN %s AND %s
"""
}, params=[start, end])
and
{% for department in departments %}
{{ department.product_count }}
{% endfor %}