简体   繁体   English

SQLAlchemy中一行的创建时间戳

[英]Creation timestamp of a row in SQLAlchemy

Using SQLAlchemy ORM, what is a good way to record the creation time of a record, without overwriting the creation time on subsequent updates?使用 SQLAlchemy ORM,有什么好的方法来记录一个记录的创建时间,而不会在后续更新时覆盖创建时间?

Here's a sample table definition:这是一个示例表定义:

class Car:
    model = Column(String, primary_key=True)
    latest_model_year = Column(Integer)
    created = Column(DateTime)

I would like to use this code to add/update a Car row in the database:我想使用此代码在数据库中添加/更新 Car 行:

car = Car(
    model = 'Accord',
    latest_model_year = 2022,
)
session.merge(car)

... but that doesn't set the created column when a new row is inserted. ...但这不会在插入新行时设置created的列。

I could do something like this:我可以做这样的事情:

if session.query(Car).filter(Car.model=='Accord').first():
    # this car already exists, so update the existing row
    car = Car(
        model = 'Accord',
        latest_model_year = 2022,
    )
    session.merge(car)
else:
    # this car does not exist, so create a new row
    car = Car(
        model = 'Accord',
        latest_model_year = 2022,
        created = datetime.now(),
    )
    session.add(car)

... but that's a lot of repetitive code. ...但这是很多重复的代码。 Is there a better way?有没有更好的办法?

Try:尝试:

from sqlalchemy.sql import func

class Car:
    model = Column(String, primary_key=True)
    latest_model_year = Column(Integer)
    created = Column(DateTime, default=func.now())  # <- HERE

Documentation: Client-Invoked SQL Expressions文档: 客户端调用的 SQL 表达式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM