0

我想实现一些映射类型,many to many例如. 例如,“apple”是“juicy fruits”的子代,同时,“apple”是许多“特定种类的苹果”的父代,而“juicy fruits”当然有很多父代喜欢“吃的东西” ”。简而言之就是关系。而且,它们都是关键字 class( ) 的实例。我将其定义如下,self referentialkeyword netmany to manyself 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

4

1 回答 1

1

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

parent=DBSession.query(KW).filter(KW.name==parentName).first()
于 2013-04-17T22:04:25.160 回答