queryset set difference

556 views
Skip to first unread message

ryan

unread,
Aug 29, 2008, 1:51:29 PM8/29/08
to Django developers
I have 2 querysets q1 and q2.

I want q3 = q2-q1, where q3 is a queryset object and contains only the
objects in q2 that are not in q1.

Is there built in support for this operation?

The only thing I can think to do is:
list( set(q2) - set(q1) )
It doesn't return a queryset, but I can deal with it if there's no
better alternative.

Thanks,
Ryan

Malcolm Tredinnick

unread,
Aug 29, 2008, 2:00:37 PM8/29/08
to django-d...@googlegroups.com

If they already exist as querysets, the set difference is the way to go.
There's probably no need to turn it back into a list at the end, since
Python's sets are iterable containers. It depends what you want to do
with it afterwards.

However, if you know the filters you are applying, you can get the
difference by changing all the filter() calls in the second queryset to
exclude() calls. So if you can hook into the process a bit earlier, you
might be able to generate a more effective SQL query.

Regards,
Malcolm


Malcolm Tredinnick

unread,
Aug 29, 2008, 2:02:56 PM8/29/08
to django-d...@googlegroups.com
And because I wasn't concentrating about which list I was reading, here
comes the obligatory statement:

Please take any follow-ups to django-users. This mailing list is
for the internal development of Django itself. "How to use"
questions should go to the django-users mailing list.

Thanks,
Malcolm


Reply all
Reply to author
Forward
0 new messages