我正在使用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
一个最小长度,或者只是禁止它成为空字符串。我怎么能这样做?
答案 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