Xerocry Xerocry - 1 year ago 60
Python Question

Check if queryset already exists

I have a list of querysets such as

([qSet1, qSet2, qSet3],[qSet3, qSet2],[qSet1, qSet3])

Then, I want to add another queryset, but only if it not already exists in list. Sets can have the same content, but in different order:
[qSet1, qSet2], [qSet2, qSet1]
. That querysets must be considered as the same => must not to be added twice.

How can I do this?

Answer Source

To check for sameness for a set of QuerySets (pun intended), you can make use of the underlying SQL query gotten from the .query method which Django provides for QuerySets. This method returns a string literal.

Say you have a list of tuples of QuerySets:

list_of_querysets = [(qSet1, qSet2, qSet3), (qSet3, qSet2), (qSet1, qSet3)]

To check if a new arbitrary tuple qsets_arb = (qSet_arb1, qSet_arb2) already has a match in the list, you would do:

def get_sql(tuple_of_querysets):
    '''Return a set of SQL statements from a tuple of QuerySets'''
    return set([str(queryset.query) for queryset in tuple_of_querysets])

# ordering of items in sets do not matter: set([q1, q2]) = set([q2, q1])
if get_sql(qsets_arb) in map(get_sql, list_of_querysets[:]):
     print("This tuple of QuerySets has already been included")

That should pretty much do what you want.