SQLAlchemy:检查两列之一的约束是否不为null? [英] SQLAlchemy: Any constraint to check one of the two columns is not null?
本文介绍了SQLAlchemy:检查两列之一的约束是否不为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这可能完全是愚蠢的事情,但是我的模型中有这样一个要求,其中至少类别
或 parent_category
不为空
This may be totally stupid thing to ask but I have such a requirement in my model where atleast either category
or parent_category
is not null
我的模型如下
class BudgetCategories(db.Model):
__tablename__ = 'budget_categories'
uuid = Column('uuid', GUID(), default=uuid.uuid4, primary_key=True,
unique=True)
budget_id = Column(GUID(), ForeignKey('budgets.uuid'), nullable=False)
budget = relationship('Budget', backref='budgetCategories')
category = Column('category', sa.types.String, nullable=True)
parent_category = Column('parent_category', sa.types.String, nullable=True)
amount = Column('amount', Numeric(10, 2), nullable=False)
recurring = Column('recurring', sa.types.Boolean,
nullable=False)
created_on = Column('created_on', sa.types.DateTime(timezone=True),
nullable=False)
我该如何指定。我什至不知道该怎么尝试
How can I specify that. I don't even know what to try
任何指针都得到赞赏
我正在使用 PostgreSQL
作为后端数据库
I am using PostgreSQL
as the backend database
推荐答案
对于<$ c $,我不确定100% c> PostgreSQL 语法,但是在添加到 BudgetCategories
模型之后,应该使用 CheckConstraint
:
I am not 100% sure about the PostgreSQL
syntax, but following addition to your BudgetCategories
model should do the trick using CheckConstraint
:
class BudgetCategories(Base):
__tablename__ = 'budget_categories'
# ...
# @note: new
__table_args__ = (
CheckConstraint('NOT(category IS NULL AND parent_category IS NULL)'),
)
这篇关于SQLAlchemy:检查两列之一的约束是否不为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文