首页 > 解决方案 > 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 想要从哪里转换objfloat

标签: pythondjangomodel

解决方案


表达方式:

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 最大的人。它只会寻找所有Profiles 中最大的重量和高度。(非常)数据可能来自两个不同 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)

但这本身并不是最新添加的对象。


推荐阅读