many-to-many queryset question

183 views
Skip to first unread message

Carsten Fuchs

unread,
Dec 6, 2011, 1:02:50 PM12/6/11
to Django users
Hi all,

looking at the example models Author and Entry at
https://docs.djangoproject.com/en/1.3/topics/db/queries/, I would like
to run a query like this:

SetOfAuthors = Authors.objects.filter(...)
qs = Entry.objects.filter(authors__in=SetOfAuthors)

such that (pseudo-code):

for e in qs:
"e.authors is a subset of (or equal to) SetOfAuthors"

However, when I try it, the true result seems to be an intersection:

for e in qs:
"There is (at least one) an author in e.authors that is also in
SetOfAuthors"


How do I have to phrase the query in order to obtain only entries whose
authors are all in SetOfAuthors?

Best regards,
Carsten

--
Cafu - the open-source Game and Graphics Engine
for multiplayer, cross-platform, real-time 3D Action
Learn more at http://www.cafu.de

Felipe Morales

unread,
Dec 6, 2011, 2:19:38 PM12/6/11
to django...@googlegroups.com
could you possibly show the query generated?... 

# print qs.query

2011/12/6 Carsten Fuchs <carste...@cafu.de>
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.




--
Felipe Morales C.
Ingenierío de Ejecución en Computación e Informática.

Peter of the Norse

unread,
Jan 6, 2012, 9:40:55 PM1/6/12
to django...@googlegroups.com
One possibility is to try two excludes.

bad_authors = Authors.objects.exclude(pk__in=SetOfAuthors)
qs = Entry.objects.exclude(authors__in=bad_authors)

This will return all entries that don't have authors in SetOfAuthors. It might even be easier, if you can skip creating SetOfAuthors in the first place.

To unsubscribe from this group, send email to django-users...@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

Peter of the Norse



Carsten Fuchs

unread,
Jan 7, 2012, 7:32:06 AM1/7/12
to django...@googlegroups.com
Hi Peter,

Am 2012-01-07 03:40, schrieb Peter of the Norse:
> One possibility is to try two excludes.
>
> bad_authors = Authors.objects.exclude(pk__in=SetOfAuthors)
> qs = Entry.objects.exclude(authors__in=bad_authors)
>
> This will return all entries that don't have authors in SetOfAuthors. It might even be
> easier, if you can skip creating SetOfAuthors in the first place.


That works very well! :-)
Thank you very much for your help!

Reply all
Reply to author
Forward
0 new messages