Django: how to annotate queryset with count of filtered ForeignKey field?

后端 未结 5 1776
猫巷女王i
猫巷女王i 2020-12-23 20:06

Django novice question :)

I have the following models - each review is for a product, and each product has a department:

class Department(models.Mod         


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-23 20:43

    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 %}
    

提交回复
热议问题