栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将对象添加到SQLAlchemy关联对象时出现KeyError

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将对象添加到SQLAlchemy关联对象时出现KeyError

问题 与您的代码是在

.__init__
方法。如果要
debug-watch/print()
使用参数,则会注意到该参数
tablet
实际上是的一个实例
Correspondent

class Tablet_Correspondent(db.Model):    def __init__(self, tablet=None, correspondent=None):        print "in __init__: ", tablet, correspondent        self.tablet = tablet        self.correspondent = correspondent

其原因是SA创建新值的方式。从文档创建新价值:

当列表

append()
事件(或set
add()
,dictionary
__setitem__()
或标量赋值事件)被关联代理拦截时,它将使用其构造函数实例化“中介”对象的新实例,并将给定值作为单个参数传递。

在您的情况下,调用时

tab.correspondents.append(cor)
,将
Tablet_Correspondent.__init__
使用单个参数调用
cor

解? 如果只添加

Correspondents
到中
Tablet
,则只需在中切换参数即可
__init__
。实际上,完全删除第二个参数。
但是,如果您还将使用
cor.tablets.append(tab)
,则需要显式使用的
creator
参数,
association_proxy
如上文链接的文档中所述:

class Tablet(db.Model, GlyphMixin):    # ...    correspondents = association_proxy('tablet_correspondents', 'correspondent', creator=lambda cor: Tablet_Correspondent(correspondent=cor))class Correspondent(db.Model, GlyphMixin):    # ...    tablets = association_proxy('correspondent_tablets', 'tablet', creator=lambda tab: Tablet_Correspondent(tablet=tab))


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/661245.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号