[FIXED] Pydantic - Dynamically create a model with multiple base classes?

Issue

From the pydantic docs I understand this:

import pydantic

class User(pydantic.BaseModel):
    id: int
    name: str

class Student(pydantic.BaseModel):
    semester: int

# this works as expected
class Student_User(User, Student):
    building: str

print(Student_User.__fields__.keys())
#> dict_keys(['semester', 'id', 'name', 'building'])

However, when I want to create a similar object dynamically (following the section dynamic-model-creation):

# this results in a TypeError
pydantic.create_model("Student_User2", __base__=(User, Student))

I get:

TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

Question: How to dynamically create a class like Student_User


Solution

As of pydantic==1.9.2,

Student_User2 = pydantic.create_model("Student_User2", __base__=(User, Student), building=(str, ...))

runs successfully and

print(Student_User2.__fields__.keys())

returns

dict_keys(['semester', 'id', 'name', 'building'])


Answered By - Ethan Chen
Answer Checked By - Katrina (Python.Easybugfix Volunteer)

Related Posts

Post a Comment