使用SQLAlchemy定义PostgreSQL字符串列的最小长度

时间:2018-05-04 11:54:45

标签: python postgresql sqlalchemy

我正在使用SQLAlchemy声明性基础定义PostgreSQL表,如下所示:

from sqlalchemy import Column, String, BigInteger
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'my_table'
    id = Column('id', BigInteger, primary_key=True)
    some_string = Column('some_string', String(256), nullable=False)

nullable约束保证some_string不能null。但是,我还想给some_string一个最小长度,或者只是禁止它成为空字符串。我怎么能这样做?

1 个答案:

答案 0 :(得分:3)

理想情况下,我们希望通过约束在数据库层应用验证,在模型中通过来应用验证,拒绝尝试将属性设置为甚至在尝试保存之前太短的字符串到数据库。我们可以使用CheckConstraint使用char_length函数执行前者,后者添加validator。以下是在some_string上强制执行最少3个字符长度的示例:

from sqlalchemy import Column, String, BigInteger
from sqlalchemy.schema import CheckConstraint
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import validates
Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'my_table'
    id = Column('id', BigInteger, primary_key=True)
    some_string = Column('some_string', String(256), nullable=False)

    __table_args__ = (
        CheckConstraint('char_length(some_string) > 2',
                        name='some_string_min_length'),
    )

    @validates('some_string')
    def validate_some_string(self, key, some_string) -> str:
        if len(some_string) <= 2:
            raise ValueError('some_string too short')
        return some_string