SQLAlchemy ORM 对relationship的属性插入数据失败。
问题描述
这几天在看《SQLAlchemy:Python数据库实战(第2版)》。在SQLAlchemy ORM这一部分,根据书上第九章的代码。在对数据进行插入的时候,orders类中有users这个属性关联到users表。当对orders插入数据的时候,会提示因为users.username是重复的而插入失败。
我想问的是:如何修改代码才是正确的插入方式?
relationship只是关联了表中的列,为何会进行实际的插入操作?
问题出现的环境背景
SQLAlchemy的版本是 1.2+
python版本是3.7
数据库是 SQLite
IDE 使用了pycharm 2019.3.3 专业版
相关代码
下面是定义表的代码
class User(Base): __tablename__ = 'users'
user_id = Column(Integer(), primary_key=True)
username = Column(String(15), nullable=False, unique=True)
email_address = Column(String(255), nullable=False)
phone = Column(String(20), nullable=False)
password = Column(String(25), nullable=False)
created_on = Column(DateTime(), default=datetime.now)
updated_on = Column(DateTime(), default=datetime.now, onupdate=datetime.now)
def __repr__(self):
return "User(username='{self.username}', " \
"email_address='{self.email_address}', " \
"phone='{self.phone}', " \
"password='{self.password}')".format(self=self)
class Order(Base):
__tablename__ = 'orders'
order_id = Column(Integer(), primary_key=True)
user_id = Column(Integer(), ForeignKey('users.user_id'))
shipped = Column(Boolean(), default=False)
user = relationship("User", backref=backref('orders', order_by=order_id)) # 这里定义了对usrs表的关联
def __repr__(self):
return "Order(user_id={self.user_id}, " \
"shipped={self.shipped})".format(self=self)
下面是插入数据时的代码
cookiemon = User(username='cookiemon', email_address='mon@cookie.com',
phone='111-111-1111',
password='password')
cakeeater = User(username='cakeeater',
email_address='cakeeater@cake.com',
phone='222-222-2222',
password='password')
pieperson = User(username='pieperson',
email_address='person@pie.com',
phone='333-333-3333',
password='password')
session.bulk_save_objects([cookiemon, cakeeater, pieperson])
session.commit()
o1 = Order()
o1.user = cookiemon
session.add(o1)
session.commit() # 提交后出现了错误
下面是报错的信息截取, SQL语句显示是在向users表中插入数据。为何只向users表中插入数据?
qlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: users.username \[SQL: INSERT INTO users (username, email\_address, phone, password, created\_on, updated\_on) VALUES (?, ?, ?, ?, ?, ?)\]
\[parameters: ('cookiemon', 'mon@cookie.com', '111-111-1111', 'password', '2020-03-31 17:58:29.156366', '2020-03-31 17:58:29.156366')\]
(Background on this error at: ![](file:///C:\Users\博博\AppData\Local\Temp\%W@GJ$ACOF(TYDYECOKVDYB.jpg)http://sqlalche.me/e/gkpj)
小弟刚开始学SQL和ORM框架,还请大神们指教。抱拳了老铁。
回答:
一对多或者是多对一,都是需要在父表中添加relationship(),外键放到引用父表的子表中
请参考:https://docs.sqlalchemy.org/e...
以上是 SQLAlchemy ORM 对relationship的属性插入数据失败。 的全部内容, 来源链接: utcz.com/p/937806.html