烧瓶,防止SQLAlchemy在实例化映射类时添加未指定的值

时间:2018-12-06 21:21:24

标签: python flask sqlalchemy flask-sqlalchemy

我上了这个课:

class Payment(db.Model):
    __tablename__ = "payment"
    id = db.Column("payment_id", db.Integer, primary_key=True, autoincrement=True)
    date = db.Column("payment_date", db.DateTime)
    payment_collected = db.Column(db.Integer)
    amount_collected = db.Column(db.String(15))
    payment_type_id = db.Column("payment_type", db.Integer)
    reference_number = db.Column(db.String(255))
    is_invoice_data = db.Column(db.Integer)
    is_active = db.Column(db.Integer)
    payee_user_id = db.Column(db.Integer, db.ForeignKey("user.user_id"))
    services_rendered_id = db.Column(
        db.Integer, db.ForeignKey("services_rendered.service_id")
    )

直接映射到数据库中的表。列payment_date(由类上的date属性表示)设置为默认为CURRENT_TIMESTAMP。但是,当像构造器一样调用此类时:

new_payment = Payment(
    services_rendered_id=new_sr.id,
    payment_collected=True,
    payment_type_id=payment_type_id,
    payee_user_id=payee_id,
    amount_collected=amount_collected
)

生成的SQL向所有映射列(包括payment_date)插入一个值,并为我在构造函数中未指定的那些列传递None。

示例:

INSERT INTO 
    payment 
        (payment_date, payment_collected, amount_collected, payment_type, reference_number, is_invoice_data, is_active, payee_user_id, services_rendered_id) 
    VALUES 
        (None, 1, '258.40', '7', None, None, None, 3240, 28)

如何避免这种行为,以使SQLAlchemy不会覆盖我在数据库中设置的默认值?

1 个答案:

答案 0 :(得分:1)

server_default=db.FetchedValue()列设置date会告诉SQLAlchemy在插入时从数据库获取该列的默认值。 See the documentation for further information.