Opened 10 years ago
Last modified 10 years ago
#22843 closed Uncategorized
contrib.auth.models.User not comparable — at Initial Version
Reported by: | ukl | Owned by: | nobody |
---|---|---|---|
Component: | Uncategorized | Version: | 1.6 |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
I stumbled over User objects not being comparable as expected in Python code. While I can order by the related User object in a query just fine this fails when sorting in Python.
The reason can be seen in the following manage.py shell session:
from django.contrib.auth.models import User
u1 = User.objects.get(id=1)
u2 = User.objects.get(id=2)
u1_ = User.objects.get(id=1)
u1 < u2
True
u2 < u1_
True
u1 < u1_
True
u1 == u1_
True
I think < compares using the object address while == uses the id attribute to compare.
A more complex example that shows the failure is:
sum(1 for _ in groupby(map(attrgetter('user'), MyModel.objects.order_by('user'))))
16
sum(1 for _ in groupby(map(attrgetter('user'), sorted(MyModel.objects.all(), key=attrgetter('user')))))
90
This means that in the first example there are 16 unique related Users in the MyModel objects. The second line finds considerably more Users because the sorting fails and so groupby doesn't detect duplicates.
I expected that both iterators MyModel.objects.order_by('user') and sorted(MyModel.objects.all(), key=attrgetter('user')) yield the same ordering.