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

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

    Avoid extra and raw whenever possible. The aggregation docs have nearly this use case:

    Straight from the docs:

    # Each publisher, each with a count of books as a "num_books" attribute.
    >>> from django.db.models import Count
    >>> pubs = Publisher.objects.annotate(num_books=Count('book'))
    >>> pubs
    [, , ...]
    >>> pubs[0].num_books
    73
    

    So, to modify this for your particular example:

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

    The function calls on separate lines is just for readability and you should move them about accordingly. I haven't tested this, but I think it should work.

提交回复
热议问题