You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SQLModel中为整数字段定义CheckConstraint约束

为SQLModel的Hero表age字段添加CheckConstraint约束

你可以通过两种方式给age字段添加年龄大于0的CheckConstraint约束:

方式一:在Field的Column参数中直接指定

直接在sa_column_kwargs里传入check条件,适合简单的单字段约束:

from sqlmodel import SQLModel, Field, Column, String, Integer
from typing import Optional


class Hero(SQLModel, table=True):
    __tablename__ = "heroes"
    id: Optional[int] = Field(default=None, primary_key=True, nullable=False)
    name: str = Field(sa_column=Column("name", String(32), unique=True), nullable=False)
    age: int = Field(sa_column=Column("age", Integer, sa_column_kwargs={"check": "age > 0"}))

方式二:通过表的__table_args__声明约束

这种方式可以给约束命名,更便于后续维护,适合多约束或需要统一管理的场景:

from sqlmodel import SQLModel, Field, Column, String, Integer
from sqlalchemy import CheckConstraint
from typing import Optional


class Hero(SQLModel, table=True):
    __tablename__ = "heroes"
    id: Optional[int] = Field(default=None, primary_key=True, nullable=False)
    name: str = Field(sa_column=Column("name", String(32), unique=True), nullable=False)
    age: int = Field(sa_column=Column("age", Integer))
    
    __table_args__ = (
        CheckConstraint("age > 0", name="hero_age_positive"),
    )

内容的提问来源于stack exchange,提问作者haku

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 17:40:57