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

后端 未结 5 1775
猫巷女王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:25

    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()
    

    EDIT

    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

提交回复
热议问题