'Django check if querysets are equals
I have this django code
q1 = MyModel.objects.all()
q2 = MyModel.objects.all()
When I try:
print(q1 == q2)
I get as a result:
False
So how can I check if two querysets results in django are equal?
Solution 1:[1]
You can convert the querysets to lists and check whether they are equal:
list(q1) == list(q2)
Solution 2:[2]
You can convert it to set, to check if 2 query sets have the same elements, without regard to ordering:
set(q1) == set(q2)
it will return:
True
Solution 3:[3]
Try this:
q1.intersection(q2).count() == q1.count() and q1.count() == q2.count()
Solution 4:[4]
Throwing in my two cents for a function that compares two QuerySets for equality while ignoring sort order. Note I'm not actually checking whether the QuerySets are empty or not; I'll leave that up to you.
def querysets_are_same(qs1, qs2, exclude_fields=[]):
'''
Check whether two queryset have the same content, sort order of querysets is ignored.
Params:
-------
qs1 (QuerySet) - first queryset to compare
qs2 (QuerySet) - second queryset to compare
exclude_fields (list) - fields to exclude from comparison; primary key field is automatically removed.
Yield:
------
True if both querysets contain the same data while ignoring sort order; False otherwise
'''
# lookup primary key field name
pk_qs1 = qs1[0]._meta.pk.name
pk_qs2 = qs2[0]._meta.pk.name
# update excluded fields
exclude_fields_qs1 = set(exclude_fields) | set([pk_qs1])
exclude_fields_qs2 = set(exclude_fields) | set([pk_qs2])
# convert queryset to list of dicts excluding fields
list_qs1 = [{k:v for k,v in d.items() if not k in exclude_fields_qs1} for d in qs1.values()]
list_qs2 = [{k:v for k,v in d.items() if not k in exclude_fields_qs2} for d in qs2.values()]
# sort lists
list_qs1_sorted = sorted(sorted(d.items()) for d in list_qs1)
list_qs2_sorted = sorted(sorted(d.items()) for d in list_qs2)
return list_qs1_sorted == list_qs2_sorted
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alasdair |
| Solution 2 | Yahya Abou Imran |
| Solution 3 | James Bond |
| Solution 4 |
