Sebastian M
Sebastian M

Reputation: 491

TypeError: Field 'classroom' expected a number but got (4,)

I have an array of arrays. Each of the nested arrays contains information about a student. I'm then iterating over it and saving each of the arrays into a student object and persisting that into my DB.

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()

The field classroom in the Student class is defines as a FloatField.

I'm getting following error:

TypeError: Field 'classroom' expected a number but got (4,).

What can be the cause for this?

EDIT 1: typo

Upvotes: 3

Views: 333

Answers (3)

Muhammad
Muhammad

Reputation: 11

I have edited your code but i think you mean to do something like this :

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))

Upvotes: 0

Eno Gerguri
Eno Gerguri

Reputation: 687

As @match has said, you have trailing commas when setting the values of your variables. Remove those and you should be good. For example:

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

No commas between setting the variables.

Upvotes: 1

Ian Wilson
Ian Wilson

Reputation: 9099

The trailing commas create tuples.

student.first_name = s[0],

Should be

student.first_name = s[0]

You can read more about that weird syntax here -- https://docs.python.org/3.3/tutorial/datastructures.html#tuples-and-sequences

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective.

Upvotes: 4

Related Questions