sqlalchemy 一对多插入出错

2014-06-23 13:58:26 +08:00
 Zuckonit
from sqlalchemy.orm import relationship
from sqlalchemy import Column, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.dialects.mysql import INTEGER, CHAR

Base = declarative_base()
class User(Base):
__tablename__ = 'user'
__table_args__ = {'mysql_engine': 'InnoDB', 'sqlite_autoincrement': True, 'mysql_charset': 'utf8'}

id = Column(INTEGER(unsigned=True), nullable=False, autoincrement=True, primary_key=True)
name = Column(CHAR(32), nullable=False)



class Address(Base):
__tablename__ = 'address'
__table_args__ = {'mysql_engine': 'InnoDB', 'sqlite_autoincrement': True, 'mysql_charset': 'utf8'}

id = Column(INTEGER(unsigned=True), nullable=False, autoincrement=True, primary_key=True)
place = Column(CHAR(32), nullable=False)
user_id = Column(INTEGER(unsigned=True), ForeignKey("user.id"), nullable=False, unique=True)
user = relationship("User", foreign_keys=[user_id], backref="addresses")


from sqlalchemy import create_engine
dsn = "mysql+mysqlconnector://test:test@localhost/test?charset=utf8&use_unicode=0"
engine = create_engine(dsn)
Base.metadata.create_all(engine)


from sqlalchemy.orm import sessionmaker
s = sessionmaker(bind=engine)()
jack = User(name='jack')
jack.addresses = [
Address(place='where'),
Address(place='here')
]
s.add(jack)
s.commit()

报错
sqlalchemy.exc.IntegrityError: (IntegrityError) 1062 (23000): Duplicate entry '3' for key 'user_id' u'INSERT INTO address (place, user_id) VALUES (%(place)s, %(user_id)s)' {'place': 'here', 'user_id': 3}
5047 次点击
所在节点    Python
4 条回复
smblog
2014-06-23 13:59:59 +08:00
Duplicate entry '3' for key 'user_id'
Zuckonit
2014-06-23 14:04:54 +08:00
@smblog 清空test数据库跑上面代码也会出错, 这个demo是在网上看的, 不知哪错了
Zuckonit
2014-06-23 14:09:11 +08:00
@Zuckonit 知道哪错了, 把unique=True去掉
wklken
2014-06-23 14:10:10 +08:00
Address

user_id = Column(INTEGER(unsigned=True), ForeignKey("user.id"), nullable=False, unique=True)

把unique去掉, 重建表.(or alter table column user_id)

外键使用unique, 插入第二个address时候,肯定报错

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/119048

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX