3

Is it possible to have "conditional" annotation in Django? Let's say, there are following models

class Author(models.Model):
   name = models.CharField()

class Article(models.Model):
   title = models.CharField()
   published = models.BooleanField()

now I'd like to select some limited (filtered) queryset of authors, and annotate them with both total books count and published books count, for later usage (like applying filters on the authors queryset, or ordering it). Something like

Author.objects.filter(name__icontains = 'a').annotate(total_books = Count('books')).annotate(published_books = Count('books', <here published=true filter>))

Is that possible anyhow?

4

2 回答 2

1

Django's ORM calls translate into SQL. If it can't be accomplished with an SQL query, it usually means you can't do it with the ORM as well. What you are requesting is a different where clause (unless I'm missing something or misunderstanding), requiring a different query. This leaves you with 2 options:

  1. Run 2 different queries (with different filter() arguments)
  2. If this is an "expensive" query that you don't want to run twice, you can just pull the data from the DB once and preform the aggregate in normal python code.
于 2013-02-10T23:26:24.937 回答
0

只是一个简单的想法,你可以尝试:

Author.objects.filter(name__icontains = 'a').\
    annotate(total_books = Count('books')).\
    annotate(published_books = Count('books__published'))

由于BooleanField写为 0/1 整数,它可以完成这项工作。或者它可能不会:) 只需在您的代码中尝试。

于 2013-05-24T06:58:11.327 回答