Files
deb-python-sqlalchemy-utils/sqlalchemy_utils/models.py
2015-03-17 17:35:55 +02:00

34 lines
990 B
Python

from datetime import datetime
import sqlalchemy as sa
class Timestamp(object):
"""Adds `created` and `updated` columns to a derived declarative model.
The `created` column is handled through a default and the `updated`
column is handled through a `before_update` event that propagates
for all derived declarative models.
::
import sqlalchemy as sa
from sqlalchemy_utils import Timestamp
class SomeModel(Base, Timestamp):
__tablename__ = 'somemodel'
id = sa.Column(sa.Integer, primary_key=True)
"""
created = sa.Column(sa.DateTime, default=datetime.utcnow, nullable=False)
updated = sa.Column(sa.DateTime, default=datetime.utcnow, nullable=False)
@sa.event.listens_for(Timestamp, 'before_update', propagate=True)
def timestamp_before_update(mapper, connection, target):
# When a model with a timestamp is updated; force update the updated
# timestamp.
target.updated = datetime.utcnow()