首页 > 解决方案 > Django:在“model_instance”和“model_instance”的实例之间不支持“<”

问题描述

我试图在我的表中为每个 ID 找到第一个和最高值,如果 if 语句为真;添加到我的柜台。

视图.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'

有什么建议吗?

标签: pythondjangodjango-viewsoperatorstypeerror

解决方案


您始终可以相信错误消息。您正在
if one < two:
比较两个Fruit无法完成的对象,除非您重载该类的<运算符我认为您只是忘记调用正确的属性,因为您只想比较水果的重量。要做到这一点,只需交换上线,如果您的模型中的 被声明为or - 实际上任何可以默认使用运算符的类型,它都会起作用。Fruit


if one.weight < two.weight:
weightIntegerFieldFloatField<


推荐阅读