Django:'model_instance' 和 'model_instance' 实例之间不支持“<”
Django: '<' not supported between instances of 'model_instance' and 'model_instance'
我正在尝试为每个 ID 在我的 table 中找到第一个和最高值,如果 if 语句为真;将它添加到我的柜台。
Views.py
keep_track = 0
# if the first weight is less than the highest weight, add +1 to the counter keep_track
for fruit in Fruits.objects.all():
one = Fruits.objects.all().first()
two = Fruits.objects.all().order_by("-weight").first()
if one < two:
keep_track += 1
print(keep_track )
我认为这是可行的,但我不太明白为什么会收到以下错误消息:
TypeError: '<' not supported between instances of 'Fruits' and 'Fruits'
有什么建议吗?
您始终可以相信错误消息。符合
if one < two:
您正在比较两个 Fruit
对象,除非您为 Fruit
class
重载 <
运算符,否则无法完成此操作
但是
我认为您只是忘记调用正确的属性,因为您只想比较水果的重量。要做到这一点,只需将上面的行换成
if one.weight < two.weight:
如果模型中的 weight
表示为 IntegerField
或 FloatField
,它将起作用 - 实际上任何类型都可以默认使用 <
运算符。
我正在尝试为每个 ID 在我的 table 中找到第一个和最高值,如果 if 语句为真;将它添加到我的柜台。
Views.py
keep_track = 0
# if the first weight is less than the highest weight, add +1 to the counter keep_track
for fruit in Fruits.objects.all():
one = Fruits.objects.all().first()
two = Fruits.objects.all().order_by("-weight").first()
if one < two:
keep_track += 1
print(keep_track )
我认为这是可行的,但我不太明白为什么会收到以下错误消息:
TypeError: '<' not supported between instances of 'Fruits' and 'Fruits'
有什么建议吗?
您始终可以相信错误消息。符合
if one < two:
您正在比较两个 Fruit
对象,除非您为 Fruit
class
重载 <
运算符,否则无法完成此操作
但是
我认为您只是忘记调用正确的属性,因为您只想比较水果的重量。要做到这一点,只需将上面的行换成
if one.weight < two.weight:
如果模型中的 weight
表示为 IntegerField
或 FloatField
,它将起作用 - 实际上任何类型都可以默认使用 <
运算符。