Equality check for two QuerySet

207 views
Skip to first unread message

mohamad ali mehdizadeh

unread,
May 10, 2022, 3:33:32 PM5/10/22
to Django developers (Contributions to Django itself)
Hi.
Why we don't have __eq__ for QuerySets, here is an example:
```
qs1 = Model.objects.all()
qs2 = qs1.all()
qs1 == qs2
```
output: False
as we know these two are the same by value!

Danilov Maxim

unread,
May 10, 2022, 3:44:51 PM5/10/22
to django-d...@googlegroups.com

I am not Agree.

qs1.all() it is copy from qs1, the new object.

 

I already try to write QuerySet compare on the Django 1.4 and i remember,

that str(qs1.query) can be different as str(qs2.query), I am not Shure.

 

Mit freundlichen Grüßen,

DI Mag. Maxim Danilov

 

+43(681)207 447 76

ma...@wpsoft.at

--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/80e878f8-8701-40ad-92a0-5c689df27ec2n%40googlegroups.com.

mohamad ali mehdizadeh

unread,
May 11, 2022, 9:41:09 AM5/11/22
to Django developers (Contributions to Django itself)
Python `==` operator does not check references, it checks values, so qs2 is a copy of qs1 but its value is the same so == must be True as it's not now.
So I have a simple solution.
def __eq__(self, other):
if not isinstance(other, self.__class__):
raise ValueError('Cannot compare a QuerySet to a non-QuerySet.')
if not self.query.can_filter():
return NotImplemented
return not self.difference(other).union(other.difference(self)).exists()

Adam Johnson

unread,
May 11, 2022, 3:47:08 PM5/11/22
to Django developers (Contributions to Django itself)
I don't think there can be a performant way to compare two querysets.

Moreover, which features should be considered in equality would be very complicated, when you consider the more involved parts of the API like database functions, annotations, subqueries, etc.

One can check via the database if two queries give the same results with the difference() method: https://docs.djangoproject.com/en/4.0/ref/models/querysets/#django.db.models.query.QuerySet.difference . For example:

querysets_the_same = not qs1.difference(qs2).exists()


Reply all
Reply to author
Forward
0 new messages