Django: TypeError: '<' not supported between instances (model objects)

我只是一个虾纸丫 提交于 2019-12-01 11:55:44

Python 3 introduces new ordering comparison:

The ordering comparison operators (<, <=, >=, >) raise a TypeError exception when the operands don’t have a meaningful natural ordering.

A simple example which prints True in Python2 and raises a TypeError in Python3

class A:
    pass

print(A() < A())

The reason is because Python 3 has simplified the rules for ordering comparisons which changes the behavior of sorting lists when their contents are dictionaries.
The ordering comparison operators (<, <=, >=, >) raise a TypeError exception when the operands don’t have a meaningful natural ordering

Also there is another interesting example

Quoting the example from the mentioned in this link

Python 2.7

>>> [{'a':1}, {'b':2}] < [{'a':1}, {'b':2, 'c':3}]
True

Python 3.5

>>> [{'a':1}, {'b':2}] < [{'a':1}, {'b':2, 'c':3}]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: dict() < dict()

The problem is that the second elements in both lists have different keys and Python doesn't know how to compare them. In earlier Python versions this has been special cased as described here by Ned Batchelder (the author of Python's coverage tool) but in Python 3 dictionaries have no natural sort order.

You can read more about the problem here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!