开发者

How to filter records before executing annotation on those records in django models?

开发者 https://www.devze.com 2023-02-22 21:09 出处:网络
In documentation is example: Book.objects.annotate(num_authors=Count(\'authors\')).filter(num_authors__gt=1)

In documentation is example:

Book.objects.annotate(num_authors=Count('authors')).filter(num_authors__gt=1)

How can I filter authors, 开发者_如何转开发before executing annotation on authors? For example I want Count only those authors that have name "John".


I don't believe you can make this selective count with the Django database-abstraction API without including some SQL. You make additions to a QuerySet's SQL using the extra method.

Assuming that the example in the documention is part an app called "inventory" and using syntax that works with postgresql (you didn't specify and it's what I'm more familiar with), the following should do what you're asking for:

Book.objects.extra(
  select={"john_count":
    """SELECT COUNT(*) from "inventory_book_authors" 
    INNER JOIN "inventory_author" ON ("inventory_book_authors"."author_id"="inventory_author"."id")
    WHERE "inventory_author"."name"=%s
    AND "inventory_book_authors"."book_id"="inventory_book"."id"
    """},
  select_params=('John',)
  )
0

精彩评论

暂无评论...
验证码 换一张
取 消