【问题标题】:TypeError: float() argument must be a string or a number, not 'Profile'TypeError:float() 参数必须是字符串或数字,而不是“配置文件”
【发布时间】: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 的地方

【问题讨论】:

标签: python django model


【解决方案1】:

表达式:

Profile.objects<b>.latest('weight')</b>

返回一个浮点值,它返回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 中最大的重量和高度。 (非常)数据可能来自两个不同的Profiles。

如果要计算Profile的BMI,可以使用:

profile = Profile.objects.get(pk=my_pk)

bmi = profile.weight / (profile.height * profile.height)

可以获得主键最大的Profilepk

profile = Profile.objects.latest('pk')

bmi = profile.weight / (profile.height * profile.height)

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

【讨论】:

  • @Monard:嗯,没有像 latest 值这样的东西。数据库可以按所有可能的顺序返回记录。你可以用最大的pk检索Profile,最后一个代码是sn-p。然而,最好在创建日期中添加时间戳,因为这是检索最新对象的唯一可靠方法。
  • 感谢您的帮助!
猜你喜欢
  • 2022-01-09
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-21
  • 2017-08-29
  • 1970-01-01
相关资源
最近更新 更多