【发布时间】:2020-10-28 20:26:00
【问题描述】:
问题:
我正在尝试从名为Profile 的模型中获取最新值。但是我遇到了一个问题,当我尝试将它作为浮点值保存到变量时,我收到此错误TypeError: float() argument must be a string or a number, not 'Profile'。我需要这个,我可以用数据进行计算。
Models.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 实例,因此您应该访问其属性 .weight 等。docs.djangoproject.com/en/3.1/topics/db/queries