Reputation: 135
I would like to define my models using pyndatic
such that the validation/serialization into mongodb
documents is done without losing information.
In particular, assuming I wish to replicate this base example with a nested serialized model:
{
"_id": "joe",
"name": "Joe Bookreader",
"addresses": [
{
"street": "123 Fake Street",
"city": "Faketon",
"state": "MA",
"zip": "12345"
},
{
"street": "1 Some Other Street",
"city": "Boston",
"state": "MA",
"zip": "12345"
}
]
}
Reference: denormalized nested model
How should I define the Pydantic models so that the instances of the sub-model Address
, once validated by creation or update (by changing the config on updates) actually contains the fields id
and name
?
I tried using some field or model validators but I figured out that if the fields are required, then they must exists when internal validation is performed to create the model and my after validator fails at runtime. I could not inject the dependency this way. The before validators seems too complex for my use case (I have a very complex nested model where properties are exploited between sub-models to implements computed fields and other logics.
If possible I would like the fields to be required, in order to have them in runtime, but not serialized when dumping the models in order to get the provided example ready to be saved onto the mongodb.
Is there an easy and smart design solution to the problem?
Upvotes: 0
Views: 20