python - 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'
有什么建议吗?
解决方案
您始终可以相信错误消息。您正在
if one < two:
比较两个Fruit
无法完成的对象,除非您重载该类的<
运算符但我认为您只是忘记调用正确的属性,因为您只想比较水果的重量。要做到这一点,只需交换上线,如果您的模型中的 被声明为or - 实际上任何可以默认使用运算符的类型,它都会起作用。Fruit
if one.weight < two.weight:
weight
IntegerField
FloatField
<
推荐阅读
- sqlalchemy - 对雪花数据库使用 sqlalchemy 时 pyformat 出错
- r - TramineR序列图与ggplot2
- android - 在lazyrow中检索当前项目
- java - LocationListener 和 Fusedlocationproviderclient 都返回空值
- ionic-framework - 如何使用标头进行离子选择(提供图片)
- excel - 有条件地格式化工作表单元格中的特定单词
- turtle-graphics - 在海龟中渲染文本
- kotlin - RecyclerView 未通过 Live Data Observer 更新
- javascript - 尝试扫描图像以从谷歌图像和带有 chrome 扩展名的雅虎图像中的图像中获取文本,但它不起作用
- git - 如何使用没有嵌套子模块的集成 git 存储库管理多个组件 git 存储库