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

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

    In django >= 2.0 this could be achieved with

    depts = Department.objects.all().annotate(
        num_products=Count('product', filter=Q(product__review__time__range=["2012-01-01", "2012-01-08"]))
    )
    

    For more info read docs https://docs.djangoproject.com/en/2.0/topics/db/aggregation/#filtering-on-annotations

提交回复
热议问题