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}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
https://www.v2ex.com/t/119048
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.