python---ORM之SQLAlchemy(5)联合唯一的使用

时间:2022-05-09 14:48:14
# coding:utf8
# __author: Administrator
# date: //
# /usr/bin/env python
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy import String,Column,Integer,ForeignKey,UniqueConstraint
from sqlalchemy.orm import relationship,sessionmaker
from sqlalchemy.ext.declarative import declarative_base engine = create_engine("mysql+pymysql://root:root@127.0.0.1/t2") Base = declarative_base() class Test(Base):
__tablename__ = 'test'
id = Column(Integer,primary_key=True)
name = Column(String())
age = Column(Integer)

  #在__table_args__中设置索引,为元组
__table_args__ = (
UniqueConstraint('name','age'),#姓名和年龄唯一
)

Base.metadata.create_all(engine) 

MySession = sessionmaker(bind=engine) 

session = MySession() 

t1 = Test(name='asd',age=) 
t2 = Test(name='asd',age=) session.add_all([t1,t2]) session.commit()

上面是可以成功的,但是当你想再添加一个,name,age相同的数据是,会报错

t3 = Test(name='asd',age=)

session.add(t3)
session.commit()
#sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError) (, "Duplicate entry 'asd-11' for key 'name'") [SQL: 'INSERT INTO test (name, age) VALUES (%(name)s, %(age)s)'] [parameters: {'name': 'asd', 'age': }] (Background on this error at: http://sqlalche.me/e/gkpj)