SQLAlchemy: Any constraint to check one of the two columns is not null?

浪子不回头ぞ 提交于 2019-12-01 20:49:23

问题


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


回答1:


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)'),
            )



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!