【问题标题】:SQLAlchemy: about self referential relation (error: no attribute '_sa_instance_state')SQLAlchemy:关于自引用关系(错误:没有属性'_sa_instance_state')
【发布时间】:2013-04-09 21:16:55
【问题描述】:

我想实现一些many to manyself referential 映射类型,例如keyword net 中的关键字图。例如,“apple”是“juicy fruits”的子代,同时,“apple”是许多“特定种类的苹果”的父代,而“juicy fruits”当然有很多父代喜欢“吃的东西” ”。简而言之,many to many 关系。而且,它们都是关键字类(self referential)的实例。我将其定义如下,

kw2kw_table=Table('kw2kw_table',Base.metadata,
              Column('child_id',Integer,ForeignKey('kw_table.id'),primary_key=True),
              Column('parent_id',Integer,ForeignKey('kw_table.id'),primary_key=True),
             )

class KW(Base):
    __tablename__='kw_table'
    id=Column(Integer,primary_key=True)
    name=Column(Unicode(28),unique=True)
    parents=relationship('KW',
                 secondary=kw2kw_table,
                 primaryjoin=id==kw2kw_table.c.child_id,
                 secondaryjoin=id==kw2kw_table.c.parent_id,
                 backref='children',
                 )
    def __init__(self,name,parent=None):
        self.name=name
        self.children=[]
        if parent==None: #default to a root keyword
            self.parents.append(self)
        else:
            self.parents.append(parent)

在我的视图文件中:

...   
    keywordName = request.params['keyword']
    parentName = request.params.get('parent',u'')
    if parentName:
        parent=DBSession.query(KW).filter(KW.name==parentName)
        if parent: #if parent exists
            new_kw=KW(keywordName,parent)
        else:
            parent=KW(parentName)
            new_kw=KW(keywordName,parent)
    else: #if the parent was not provided
        new_kw=KW(keywordName)
    DBSession.add(new_kw)
...

但是,当使用(keyword,parent) 提交视图时,出现错误:

File "build/bdist.macosx-10.6-intel/egg/sqlalchemy/orm/attributes.py", line 910, in fire_append_event
value = fn(state, value, initiator or self)
File "build/bdist.macosx-10.6-intel/egg/sqlalchemy/orm/attributes.py", line 1138, in emit_backref_from_collection_append_event
child_state, child_dict = instance_state(child), \
AttributeError: 'Query' object has no attribute '_sa_instance_state'

我用谷歌搜索了它,但无法弄清楚。请帮忙。

---------更新------------

详情: https://gist.github.com/actor2019/5417471

【问题讨论】:

    标签: python sql orm sqlalchemy pyramid


    【解决方案1】:

    您需要调用 Query 以便取回一个实例,现在您正在将 Query 对象传递给您的 Session:

    parent=DBSession.query(KW).filter(KW.name==parentName).first()
    

    【讨论】:

    • 谢谢。错误消失了,我在parent=KW(parentName)new_kw=KW(keywordName,parent) 之间添加了DBSession.add(parent)。但是还是不行(我提交数据后没有提交新的关键字)...看来__init__没有达到我的预期。
    • 您是否正在刷新/提交会话?
    • 再次感谢您的回复。 Pyramid 文档说“Pyramid 负责提交:它在请求结束时提交,如果出现异常则中止。”无论如何,即使我手动进行冲洗,它也不起作用。我在这里粘贴了控制台输出:gist.github.com/actor2019/5417471
    • 在我们的 ini 文件中,您的 pyramid.includes 中有 'pyramid_tm' 吗?这就是在 Web 请求结束时自动提交的神奇模块。
    猜你喜欢
    • 1970-01-01
    • 2016-01-10
    • 2018-12-23
    • 2021-12-27
    • 2022-11-06
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多