【问题标题】:TypeError: Field 'classroom' expected a number but got (4,)TypeError:字段“教室”需要一个数字但得到(4,)
【发布时间】:2020-06-22 20:50:27
【问题描述】:

我有一个数组数组。每个嵌套数组都包含有关学生的信息。然后我将对其进行迭代并将每个数组保存到一个学生对象中并将其持久化到我的数据库中。

students = [
    ["James", "Smith", 4, 10],
    # more students here
]

for s in students:
    student = Student()
    student.first_name = s[0],
    student.last_name = s[1],
    student.classroom = s[2],
    student.grade1 = s[3],
    student.save()

Student 类中的字段classroom 定义为FloatField

我收到以下错误:

TypeError: 字段 'classroom' 需要一个数字,但得到 (4,)。

这可能是什么原因?

编辑 1:错字

【问题讨论】:

  • 问题是所有变量行的尾随逗号。您实际上是在将值设置为 4,
  • 使用 float(s[2]) 不起作用。 @match 如何更改线路以使其正常工作?
  • 去掉逗号。

标签: python python-3.x django django-models


【解决方案1】:

尾随逗号创建元组。

student.first_name = s[0],

应该是

student.first_name = s[0]

你可以在这里阅读更多关于这种奇怪语法的信息—— https://docs.python.org/3.3/tutorial/datastructures.html#tuples-and-sequences

一个特殊的问题是包含 0 或 1 的元组的构造 items:语法有一些额外的怪癖来适应这些。空的 元组由一对空括号构成;一个元组 一个项目是通过在一个带有逗号的值后面构造的(它不是 足以将单个值括在括号中)。丑,但是 有效。

【讨论】:

    【解决方案2】:

    正如@match 所说,在设置变量的值时,您有尾随逗号。删除那些,你应该很好。例如:

    student.first_name = s[0]
    student.last_name = s[1]
    student.classroom = s[2]
    student.grade1 = s[3]
    student.save()
    

    设置变量之间没有逗号。

    【讨论】:

      【解决方案3】:

      我已经编辑了你的代码,但我认为你的意思是这样做:

      s = [
          ["James", "Smith", 4, 10],
          # more students here
      ]
      
      class Student:
       
          def __init__(self,first_name,last_name,classroom,grade):
              """ Create a new point at the origin """
              self.first_name = first_name
              self.last_name = last_name
              self.classroom = classroom
              self.grade = grade
      
      
      student = Student(s[0][0],s[0][1],s[0][2],s[0][3])
      
      from pprint import pprint
      pprint(vars(student))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-26
        • 1970-01-01
        • 2021-06-25
        • 2021-08-31
        • 2021-07-20
        • 2021-12-02
        • 1970-01-01
        相关资源
        最近更新 更多