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
My model looks like
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
Any pointers appreciated
I am using PostgreSQL as the backend database
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)'),
)
I hope is not too late but this should do the trick and it is checked to work with a PostGreSQL DB:
class BudgetCategories(Base):
__tablename__ = 'budget_categories'
__table_args__ = (
CheckConstraint('coalesce(category , parent_category ) is not null'),
)
# ...
来源:https://stackoverflow.com/questions/20943777/sqlalchemy-any-constraint-to-check-one-of-the-two-columns-is-not-null