Unfortunately, on the python side, sqlalchemy does its best to stay out of the way; there is no special sqlalchemy form to express that an instance attribute must satisfy some restriction:
>>> class Foo(Base): ... __tablename__ = 'foo' ... id = Column(Integer, primary_key=True) ... bar = Column(Integer) ... >>> f = Foo() >>> f.bar = "not a number!" >>> f.bar 'not a number!'
If you tried to commit this object, sqlalchey will complain because it does not know how to display the provided python value as SQL for the Integer column type.
If this is not what you are looking for, you just want to make sure that bad data does not reach the database, then you need Check Constraint.
class Foo(Base): __tablename__ = 'foo' id = Column(Integer, primary_key=True) bar = Column(Integer) __table_args__ = ( CheckConstraint(bar >= 0, name='check_bar_positive'), {})
source share