使用 SQLAlchemy 定义 PostgreSQL 字符串列的最小长度 [英] Define minimum length for PostgreSQL string column with SQLAlchemy

查看:84
本文介绍了使用 SQLAlchemy 定义 PostgreSQL 字符串列的最小长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm defining an PostgreSQL table using an SQLAlchemy declarative base, like this:

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 一个最小长度,或者只是禁止它成为空字符串.我该怎么做?

The nullable constraint guarantees that some_string cannot be null. However, I'd additionally like to give some_string a minimum length, or just forbid it from being the empty string. How can I do this?

推荐答案

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

Ideally we want the validation to be applied both at the database layer via a constraint and also in our model by rejecting attempts to set the property to a string that's too short even before trying to save it to the database. We can do the former with a CheckConstraint using the char_length function, and the latter by adding a validator. Below is an example that enforces a minimum length of 3 characters on some_string:

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

这篇关于使用 SQLAlchemy 定义 PostgreSQL 字符串列的最小长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆