pydbantic icon indicating copy to clipboard operation
pydbantic copied to clipboard

Add a field with datetime.utcnow in documentation example

Open sorasful opened this issue 4 years ago • 3 comments

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 ?

sorasful avatar Nov 15 '21 21:11 sorasful

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.

codemation avatar Nov 16 '21 08:11 codemation

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 avatar Nov 17 '21 14:11 sorasful

@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.

codemation avatar Nov 17 '21 14:11 codemation