Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In SQLAlchemy, how do I create a 'MySQL date' column?

class Posts(Base):
    __tablename__ = 'posts_posts'
    id = Column(Integer, primary_key = True)
    user_id = Column(Integer, nullable=False)
    body = Column(Text, nullable=True)

    created_at = Column(Date) << is this right?
    updated_at = Column(Date) ??

I would also like the created_at column to automatically set the date when it's created. And also, the updated_at column to set the date anytime this row is changed.

like image 669
TIMEX Avatar asked Nov 26 '11 08:11

TIMEX


People also ask

How do I create a date column in SQLAlchemy?

Bookmark this question. Show activity on this post. class Posts(Base): __tablename__ = 'posts_posts' id = Column(Integer, primary_key = True) user_id = Column(Integer, nullable=False) body = Column(Text, nullable=True) created_at = Column(Date) << is this right?

Can you use SQLAlchemy with MySQL?

SQLAlchemy supports MySQL starting with version 5.0. 2 through modern releases, as well as all modern versions of MariaDB.

What is column in SQLAlchemy?

function sqlalchemy.orm. column_property(*columns, **kwargs) Provide a column-level property for use with a mapping. Column-based properties can normally be applied to the mapper's properties dictionary using the Column element directly.


1 Answers

You can provide default and onupdate parameters to Column:

def _get_date():
    return datetime.datetime.now()

class Posts(Base):
    #...
    created_at = Column(Date, default=_get_date)
    updated_at = Column(Date, onupdate=_get_date)

See Column documentation for more info on this one.

like image 137
van Avatar answered Sep 19 '22 15:09

van