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

Viewed 32

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    age = Column(Integer)# i need age to have mix value of 0 and max of 100 
    email = Column(String)

sqlalchemy documentation says that there no such atributes to pass while creating a column

2 Answers

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}')
Related