I'm using pydantic to model objects which are then being serialized to json and persisted in mongodb For better encapsulation, I want to some fields to be private but I still want them to be serialized to json when saving to mongodb, and then deserialized back from json when I fetch the object from the db
how can this be done?
Example Model:
class MyModel(BaseModel):
public_field: str
_creation_time: str
def __init__(self, public_field: str):
super().__init__(public_field=public_field,
_creation_time=str(datetime.now()))
model = MyModel(public_field='foo')
json_str = model.json()
print(json_str)
The output of this code is:
{"public_field": "foo"}
I would like it to be something like this:
{"public_field": "foo", "_creation_time": "2023-03-03 09:43:47.796720"}
and then also to be able to deserialize the above json back with the private field populated