代码:
python
from sqlmodel import Field, Session, SQLModel, create_engine
# 声明模型
class User(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
# 不能为空,必须唯一
name: str = Field(nullable=False, unique=True)
age: int | None = None
# 创建引擎
engine = create_engine("sqlite:///database.db", echo=True)
# 创建表
SQLModel.metadata.create_all(engine)
# 创建两个名字重复的用户
zs_1 = User(name="张三", age=22)
zs_2 = User(name="张三", age=23)
with Session(engine) as session:
session.add(zs_1)
session.add(zs_2)
session.commit()
这段代码执行,会触发唯一性校验异常:
如果注释掉其中一个,则正常执行:
python
from sqlmodel import Field, Session, SQLModel, create_engine
# 声明模型
class User(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
# 不能为空,必须唯一
name: str = Field(nullable=False, unique=True)
age: int | None = None
# 创建引擎
engine = create_engine("sqlite:///database.db", echo=True)
# 创建表
SQLModel.metadata.create_all(engine)
# 创建两个名字重复的用户
zs_1 = User(name="张三", age=22)
# zs_2 = User(name="张三", age=23)
with Session(engine) as session:
session.add(zs_1)
# session.add(zs_2)
session.commit()