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
2010-06-04 13:51:17
+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
2010-06-04 14:29:43
+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
2010-06-04 15:12:08
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
2010-06-04 15:31:48
+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
2010-06-04 19:08:19