views:

115

answers:

3

Consider two QuerySet objects of the same class. Is there a simple way to unify them into a single QuerySet, similar to addition but without duplicates. Also, is there a simple way to subtract them? Removing all elements that appear in both sets from one of the sets?

+1  A: 

I think for operations as this you need to evalute them. So you can call list() on them and work on them with the common python list operations!

lazerscience
+3  A: 

You can use the Q object.

The syntax could be something like this:

added_query_set = YourModel.objects.\
         filter(Q(id__in=old_query_set_1)|Q(id__in=old_query_set_2))

You probably can optimize based on your actual needs and get the amount of db hits down (right now it's 3), but this should get you started.

Zach
+1 for doing it nicely with querysets, but i guess it's even hitting the db one time more than adding lists! i guess which method you prefer depends on if you want an unevaluated qs or lesser db hits!
lazerscience
Given the actual parameters of the two original `QuerySet`s you should be able to include those parameters in the `Q` objects and get down to one db hit
Zach
+1  A: 

Going back to django's documentation, you can:

new_query_set = query_set_1 | query_set_2

This works as a logical OR which is actually addition without duplicates. This answers the addition aspect and AFAIK does not hit the db at all!

new_query_set = query_set_1 & query_set_2

This works as a logical AND.

Still missing how to subtract QuerySets. It's hard for me to believe this has not been dealt with elegantly by the community...

Jonathan