Python TypeError:float()参数必须是字符串或数字,而不是';简介'; 问题:
我正在尝试从名为Python TypeError:float()参数必须是字符串或数字,而不是';简介'; 问题:,python,django,model,Python,Django,Model,我正在尝试从名为Profile的模型中获取最新的值。但我遇到了一个问题,当我试图将其作为浮点值保存到变量时,我得到了以下错误TypeError:float()参数必须是字符串或数字,而不是“Profile”。我需要这个,这样我就可以用数据进行计算 Models.py文件: Views.py文件(相关部分): 我在这里搜索了这个错误代码,但没有找到ppl想要从obj转换为float表达式的任何错误代码: Profile.objects.latest('weight') 请注意,这本身并不是体重指数
Profile
的模型中获取最新的值。但我遇到了一个问题,当我试图将其作为浮点值保存到变量时,我得到了以下错误TypeError:float()参数必须是字符串或数字,而不是“Profile”
。我需要这个,这样我就可以用数据进行计算
Models.py文件:
Views.py文件(相关部分):
我在这里搜索了这个错误代码,但没有找到ppl想要从obj
转换为float
表达式的任何错误代码:
Profile.objects.latest('weight')
请注意,这本身并不是体重指数最大的人。它只需查找所有Profile
s中最大的重量和高度。(非常)数据很可能来自两个不同的Profile
s
如果要计算档案的体重指数
,可以使用:
profile = Profile.objects.get(pk=my_pk)
bmi = profile.weight / (profile.height * profile.height)
但这本身并不是最新添加的对象。它确实返回整个配置文件实例,因此您应该访问它的属性。权重等。@Monard:没有最新值。数据库可以按任何可能的顺序返回记录。您可以使用最大的
pk
和最后一个代码片段检索Profile
。不过,最好添加一个带有创建日期的时间戳,因为这是检索最新对象的唯一可靠方法。谢谢您的帮助!
Profile.objects.latest('weight')
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)
profile = Profile.objects.get(pk=my_pk)
bmi = profile.weight / (profile.height * profile.height)
profile = Profile.objects.latest('pk')
bmi = profile.weight / (profile.height * profile.height)