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

flask-sqlalchemy, postgresql, python, sqlalchemy

Solution

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

Problem

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

Original source

Related problems