views:

51

answers:

1

Is there a way to transform a QuerySet to a Q object in django?

My specific motivation: I would like to subtract one QuerySet (qs_A) from another QuerySet (qs_B). The only way I can think of is by using exclude() and a Q object equivalent of qs_A.

Example:

def my_function(qs_A, qs_B):
    # Here I need to transform qs_A to a Q object q_obj_A
    qs_new = qs.exclude(q_obj_A)
    return qs_new
+4  A: 

You don't need a Q object. Just exclude the second queryset:

qs = qs_a.exclude(id__in=qs_B)
Daniel Roseman
That's simple and would work, but I suspect it's less efficient and more db intensive, at least in many cases, than actually having a Q object that represents a simple condition.
Jonathan
Premature optimisation is the root of all evil. Or at the very least, bad.
Matthew Schinckel
@Matthew - do you mean to say that django is a premature web framework?! Or did you mean that my project is premature?!
Jonathan
@Daniel - I guess your answer is NO, there is no way to transform a QuerySet to a Q object. Could you confirm so I can accept this answer?
Jonathan
Not that I know of. They're fundamentally different things.
Daniel Roseman
@Jonathon: neither. Wait until you know that the solution is no longer feasible. Watch your db logs, and determine if this code is causing performance issues.
Matthew Schinckel