Search code examples
djangodjango-ormdjango-postgresql

django orm equivalent for "group by sth. having every(sth.)"


Suppose I have a model "Book" with three fields: name, author_name (as a string), publish_state. Now I want to find out which authors have exactly one published book. This sql query does exactly what I want:

SELECT author_name from books GROUP BY author_name HAVING count(name) = 1 and every(publish_state = 'published');

I'm using Postgres as you can say by the 'every' clause.

Is there a way to do this in django ORM? or do I need to use a raw query for that?


Solution

  • Unfortunately this feature is not implemented in django's ORM, and I don't think it would be any time soon, as it is not a very common query.

    I had to use raw SQL. You can find about it here: https://docs.djangoproject.com/en/1.7/topics/db/sql/