python---ORM之SQLAlchemy(5)联合唯一的使用
# coding:utf8 # __author: Administrator # date: 2018/3/16 0016 # /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(40)) 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=11)
t2 = Test(name='asd',age=12)
session.add_all([t1,t2])
session.commit()
上面是可以成功的,但是当你想再添加一个,name,age相同的数据是,会报错
t3 = Test(name='asd',age=11) session.add(t3) session.commit()
#sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError) (1062, "Duplicate entry 'asd-11' for key 'name'") [SQL: 'INSERT INTO test (name, age) VALUES (%(name)s, %(age)s)'] [parameters: {'name': 'asd', 'age': 11}] (Background on this error at: http://sqlalche.me/e/gkpj)