Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's equivalent to Django's auto_now, auto_now_add in SQLAlchemy?

In Django, we can use these 2 parameters when making a date column:

DateField.auto_now Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.

DateField.auto_now_add Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override.

How to do this in SQLAlchemy?

like image 764
zchenah Avatar asked Feb 28 '13 13:02

zchenah


People also ask

What is the difference between Auto_now and Auto_now_add?

From django docs: “”" auto_now Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it's not just a default value that you can override. auto_now_add Automatically set the field to now when the object is first created.

What is Auto now and auto Now add in Django?

The auto_now_add will set the timezone. now() only when the instance is created, and auto_now will update the field everytime the save method is called. It is important to note that both arguments will trigger the field update event with timezone.


1 Answers

Finally, after checking the SQLAlchemy doc, this should be the way:

Column('created_on', DateTime, default=datetime.datetime.now)

Column('last_updated', DateTime, onupdate=datetime.datetime.now)

doc here:

http://docs.sqlalchemy.org/en/latest/core/defaults.html#python-executed-functions

like image 75
zchenah Avatar answered Sep 27 '22 23:09

zchenah