Search code examples
pythonsqlalchemyintegermaxmin

Is there a way to specify min and max values for integer column in slqalchemy?



class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    age = Column(Integer) # I need age to have min value of 0 and max of 100 
    email = Column(String)

SQLAlchemy documentation says that there is no such attributes to pass while creating a column


Solution

  • As described in brunson's answer, you can add a check constraint to perform the validation in the database, if the database supports check constraints.

    import sqlalchemy as sa
    ...
    class Test(Base):
        __tablename__ = 'test'
    
        id = sa.Column(sa.Integer, primary_key=True)
        age = sa.Column(sa.Integer, sa.CheckConstraint('age > 0 AND age < 100'))
    

    It may be more convenient to perform the validation before data is sent to the database, in the application layer. In this case, the orm.validates decorator can be used:

    class Test(Base):
        __tablename__ = 'test'
    
        id = sa.Column(sa.Integer, primary_key=True)
        age = sa.Column(sa.Integer, sa.CheckConstraint('age > 0 AND age < 100'))
    
        @orm.validates('age')
        def validate_age(self, key, value):
            if not 0 < value < 100:
                raise ValueError(f'Invalid age {value}')
            return value