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

Question:


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

Asked By: motorenger

||

Answers:

This is probably because none of the RDBMSes I’m familiar with support min/max in the column definition.

If you need to enforce that you can write a trigger or if your DB supports it you can add a check constraint.

https://dev.mysql.com/blog-archive/mysql-8-0-16-introducing-check-constraint/

Answered By: brunson

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
Answered By: snakecharmerb
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.