Django Many-to-many Query: Publications with no Articles? Publications with some Articles?

32 views
Skip to first unread message

Edward Sitarski

unread,
Aug 21, 2015, 3:49:36 PM8/21/15
to Django users
I have read the Django Many to Many documentation.

Based on the example, I am stuck on how to formulate the following queries (this related to my "real life" problem):
  1. What Publications have no Articles?
  2. What Publications have at least one Article?
Doing it with a loop is straightforward:

publications_with_no_articles = [publication for publication in Publication.objects.all() if not publication.article_set.all().exists()]
publications_with_some_articles = [publication for publication in Publication.objects.all() if publication.article_set.all().exists()]

But, that's slow if you have a lot of publications - a query for each one.
Is there a way to formulate the queries with no loop, returning a QuerySet?

Apologies in advance if I am missing something simple...

Shawn Milochik

unread,
Aug 21, 2015, 4:02:39 PM8/21/15
to django...@googlegroups.com
No articles:
Publication.objects.filter(article_set=None)

Has articles:
Publication.objects.exclude(article_set=None)

Edward Sitarski

unread,
Aug 24, 2015, 11:33:16 AM8/24/15
to Django users, Sh...@milochik.com
Thanks - didn't see that one.
For my own reference/sanity, can you attach a link where this is documented?
I should have found this one before too.


Shawn Milochik

unread,
Aug 24, 2015, 11:36:07 AM8/24/15
to django...@googlegroups.com
I couldn't find it in Django's documentation; just from StackOverflow and another source (both found via Google).

I always used to do something like Thing.objects.filter(other__id__isnull=True) to do that, but clearly this is better.
Reply all
Reply to author
Forward
0 new messages