Add a field with datetime.utcnow in documentation example
Hi there,
Working with dates can be quite challenging, for example when trying to add something like "creation_date" or "updated_at" in plain SQLalchemy we would do something like :
from sqlalchemy.sql import func
time_created = Column(DateTime(timezone=True), server_default=func.now())
time_updated = Column(DateTime(timezone=True), onupdate=func.now())
How would we be able to achieve the same thing in Pydbantic ?
What you are describing is possible by using Default() in the model definition, also possible with PrimaryKey() as well, by feeding a function with no arguments
from datetime import datetime
from pydbantic import DataBaseModel, PrimaryKey, Default
def time_now():
return datetime.now()
class Dates(DataBaseModel):
create_time: datetime = PrimaryKey(default=time_now)
update_time: datetime = Default(default=time_now)
Take note that, in the above format, the datetime objects will be serialized as datetime objects, if you want to store as a string or other, adjust the type annotation & time_now() method.
It looks a little bit weird to me to have a PrimaryKey set as a datetime.
But anyway, your example with the update time seems nice.
It should be added in the documentation I'll do a PR if you want.
@sorasful PR's are always welcome, especially those which improve documentation.
Small Note on Updating Documentation
Install mkdocs
pip install mkdocs
View Docs Locally
$ mkdocs serve
Improve Docs within README.md or /docs/ and create a Pull Request. Also please close this issue now or along with your PR when you get the chance.