Skip to content
Advertisement

Pydantic created at and updated at fields

I’m new to using Pydantic and I’m using it to set up the models for FastAPI to integrate with my postgres database. I want to make a model that has an updated_at and created_at field which store the last datetime the model was updated and the datetime the model was created. I figured created_at could be something like this:

JavaScript

How would I do an updated_at so it updates the datetime automatically every time the model is updated?

Advertisement

Answer

You can use a validator which will update the field updated_at each time when some other data in the model will change. The root_validator and the validate_assignment config attribute are what you are looking for.

This is the sample code:

JavaScript

and the output:

JavaScript

You can see that there is a difference in microseconds after object creation. If this is a problem you can set:
updated_at: Optional[datetime] = None
and modify the validator like this:

JavaScript

and the new output:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement