python - TypeError:float() 参数必须是字符串或数字,而不是“配置文件”
问题描述
问题:
我正在尝试从名为Profile
. 但是我遇到了一个问题,当我尝试将它作为浮点值保存到变量时,我得到了这个错误TypeError: float() argument must be a string or a number, not 'Profile'
。我需要这个,我可以用数据进行计算。
模型.py 文件:
class Profile(models.Model):
weight = models.FloatField()
height = models.FloatField()
bmi = models.FloatField(null=True)
date = models.DateField(auto_now_add=True)
user = models.ForeignKey(User, default=None, on_delete=models.CASCADE)
def __str__(self):
return self.user.username
Views.py 文件(相关部分):
weight = float(Profile.objects.latest('weight'))
height = float(Profile.objects.latest('height'))
bmi = (weight/(height**2))
我在这里搜索了这个错误代码,但我没有找到任何 ppl 想要从哪里转换obj
为float
解决方案
表达方式:
Profile.objects.latest('weight')
不返回浮点值,它返回Profile
最高的 weight
。但不是重量本身。
.aggregate(…)
但是,您可以通过[Django-doc]轻松获得这两个值:
from django.db.models import Max
result = Profile.objects.aggregate(
max_weight=Max('weight'),
max_height=Max('height')
)
weight = result['max_weight']
height = result['max_height']
bmi = weight / (height * height)
请注意,这本身并不是bmi 最大的人。它只会寻找所有Profile
s 中最大的重量和高度。(非常)数据可能来自两个不同 Profile
的 s。
如果要计算 a 的 BMI Profile
,可以使用:
profile = Profile.objects.get(pk=my_pk)
bmi = profile.weight / (profile.height * profile.height)
您可以获得Profile
具有最大主键的pk
:
profile = Profile.objects.latest('pk')
bmi = profile.weight / (profile.height * profile.height)
但这本身并不是最新添加的对象。
推荐阅读
- c# - 如何屏蔽radtextbox中的一些文本
- apache - 当有多个证书可用时,Apache 如何知道使用哪个证书?
- reactjs - 反应无法设置未定义的属性'scrollTop'
- reactjs - 使用 React 的 Bot Framework 语音到文本集成问题
- sqlite - 如何在 Sqflite for Flutter 中使用准备好的语句
- java - 尽管不使用锁定,比较和设置如何工作
- java - Java 8:使用 andThen() 和 apply() 方法时 BiFunction 如何工作
- cassandra - Cassandra 3.10 - 泄漏检测和流失败
- java - 用 Java 创建 kafka 主题不起作用
- python - csv 文件在“w”模式下不写入