sqlalchemy可以添加字段级规则,即两个特定的列不能都都为None?

时间:2018-09-10 14:47:25

标签: python sqlalchemy flask-sqlalchemy

我有一个看起来像这样的模型:

class Foo(db.Model):

    id = db.Column(db.Integer, primary_key=True)

    # omitted lengthy codes...

    spam = db.relationship('Spam')
    spam_id = db.Column(db.Integer, db.ForeignKey('spams.id'))

    bar = db.relationship('Bar')
    bar_id = db.Column(db.Integer, db.ForeignKey('bars.id'))

    created = db.Column(db.DateTime, server_default=db.func.now())

Flask-SQLAlchemy是否有可用的选项来添加在插入/更新期间spam_idbar_id不能同时为None的行为?但是如果这些列中至少有一个具有值,则将接受。

1 个答案:

答案 0 :(得分:1)

您可以使用table constraint here

from sqlalchemy import CheckConstraint


class Foo(db.Model):

    id = db.Column(db.Integer, primary_key=True)

    # omitted lengthy codes...

    spam = db.relationship('Spam')
    spam_id = db.Column(db.Integer, db.ForeignKey('spams.id'))

    bar = db.relationship('Bar')
    bar_id = db.Column(db.Integer, db.ForeignKey('bars.id'))

    created = db.Column(db.DateTime, server_default=db.func.now())

    __table_args__ = (
        CheckConstraint('NOT(spam_id IS NULL AND bar_id IS NULL)', name='both_null'),
    )

试图添加一个带有spam_id且没有None的新Foo实例?好吧你可以

foo=Foo(spam_id=None, bar_id=1)
sqlalchemy_session.add(foo)
sqlalchemy_session.commit()

试图添加同时具有spam_id和bar_id的Foo为None?不,先生!

foo=Foo(spam_id=None, bar_id=None)
sqlalchemy_session.add(foo)
sqlalchemy_session.commit()  # Raises Exception

引发的异常来自您的DBMS,例如PostgresQL和psycopg2驱动程序为psycopg2.IntegrityError