Joerg Baach
Joerg Baach

Reputation: 1086

Dynamic created nested model in pydantic

In my use case I need to create nested models dynamically, reusing model elements. E.g. I'd like to define an adress model, and resue it for a person model:

from pydantic import Field, create_model

name = Field('a name')
street = Field('a street')
city = Field('a city')
address = create_model('address', street=street, city=city)
person = create_model('person', name=name, address=address)

locationdata = dict(street='somestreet', city='sometown')
print(address.parse_obj(locationdata).dict())

alicedata = dict(name='alice', address=locationdata)
print(person.parse_obj(alicedata).dict())

# Gives:
#
# {'street': 'somestreet', 'city': 'sometown'}
# {'name': 'alice'}

The locationdata never 'reaches' the person, although used directly it works. Any suggestions? Is create_model the right tool for the job?

Upvotes: 0

Views: 1413

Answers (1)

alex_noname
alex_noname

Reputation: 32143

You need to create person as:

person = create_model('person', name=name, address=(address, ...))  # address model, required
# OR
person = create_model('person', name=name, address=address())  # instantiate default value

Because create_model defines fields by either a tuple of the form (<type>, <default value>) or just a default value.

Upvotes: 1

Related Questions