简体   繁体   中英

How to generate attributes dynamically in pydantic?

Let's say we have this list of names:

students = ['A','B','C']

and I have this model with pydantic:

class Student(BaseModel):
    name: str
    rank: int = 0

and I have this model that I want to fill the students in it dynamically and have like a template:

class MathClass(BaseModel):
    def __init__(self, student_names):
        self.students = []
        for student_name in student_names:
             self.students.append(Student(name=student_name))

When I launch my code with

math_class=MathClass(students)

I get this error:

ValueError: "MathClass" object has no field "students"

Why is that happening? is there a better way to do it?

I think the issue has to do with not defining students in the model itself as well as not calling __init__() on the inherited class. I was able to get your code to run by modifying MathClass like so:

class MathClass(BaseModel):
   students: list = []
    
   def __init__(self, student_names: list):
        super().__init__()

        for student_name in student_names:
            self.students.append(Student(name=student_name))

Best of luck and happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM