2011-11-29 27 views
3

注意這是在SQLAlchemy 0.5.7中。看來,這是不可能的,因爲「懶惰」不適用於一對一映射。如果確實如此,我認爲它錯了,請發佈您的答案。SQLAlchemy中的UnboundExecutionError


我有以下的方法,該方法應該返回任何類的父Parent的所有實例。請注意,類Child有一個屬性fubar,這是另一個類。我已經在其他地方正確映射了它

def get_all(self): 
    session = self.__Session() 
    lst = session.query(Parent).with_polymorphic('*').all() 
    #print lst # <-- this commented back in and it all works. 
    session.expunge_all() 
    session.close() 
    return lst 

然後,我可以做的事情,如for item in get_all(): [...]和所有。在child的映射中,我有lazy-False,所以我會假設它會被正確加載。但是,如果我離開評論在打印行,我得到的是這樣的例外:

UnboundExecutionError: Parent instance <Child at 0xa1bca4c> is not bound to a Session; lazy load operation of attribute 'fubar' cannot proceed 

我不明白的事情是這樣的:當打印線是存在的,對象確實是裝的罰款。

我在做什麼錯?

編輯:感謝@van,我認爲fubar對象確實是以懶惰的方式加載的。我在映射以下幾點:

sqlalchemy.orm.mapper(Child, tb_child, inherits=Parent, 
    polymorphic_identity='Child', properties={'fubar': 
     sqlalchemy.orm.relation(Child, 
       lazy=False, 
       uselist=False, 
       cascade="all, delete-orphan") 
      } 
     ) 

父的代碼是這樣的:?

sqlalchemy.orm.mapper(Parent, 
     tb_parent, 
     polymorphic_on=tb_parent.c.type, 
     polymorphic_identity='Parent') 

什麼不對這個...

另外,我怎麼能強迫query()以非懶惰的方式加載所有內容?

+0

「Parent」的'repr'是否也打印出'Child'?所以它是由於非常'印刷'加載?啓用'echo = True'並查看'print'是否在'print'時加載了'Child'。 – van

+0

@van:是的,「家長」的代表確實稱爲孩子的「代表」。是的,它看起來像'fubar'對象是懶加載的。該死!問題已更新。謝謝。 – Sardathrion

+0

但在您的編輯中,我沒有看到任何「fubar」關係定義,只有「ref」...? – van

回答

2

Relationship API documentation(向下滾動到lazy參數的說明):

lazy=’select’ – specifies how the related items should be loaded. Default value is select. Values include: 
    ... 
    noload - no loading should occur at any time. This is to support 「write-only」 attributes, or attributes which are populated in some manner specific to the application. 
    ... 
    True - a synonym for ‘select’ 
    False - a synonyn for ‘joined’ 
    None - a synonym for ‘noload’ 

因此,通過設置lazy=None你實際上沒有配置關係,急於裝,但得到幾乎相反的結果。您應該使用以下其中一個:immediate, joined or subquery

編輯-1:中,因爲事實上,SA-0.5用於:我不知道爲什麼的關係並不急切地加載,但你可能會試圖在查詢中顯式地指定它,看看它的工作原理:

lst = (session.query(Parent).with_polymorphic('*'). 
    options(eagerload('fubar')).all()) # confused if it is "fubar" or "ref" 
+0

任何指向0.5版的指針的機會?是的,我正在研究一個只安裝了它的遺留系統。我*可以*更新,但這將是一個艱難的銷售。謝謝。我能找到的只有:'lazy =(真|假|無|'動態')'這並沒有什麼幫助。 – Sardathrion

+0

在附註中,我使用'lazy = False'以及0.5版本,這可能會有所作爲。 – Sardathrion

+0

事實上,SA版本在這裏很重要。你能否提供Parent的映射代碼?我發現有一點讓人困惑,一個孩子的polymorphic_identity是'Parent'...另外,這個關係「ref」的性質是什麼?基數?我想知道「懶惰」在0.5中是否適用於「一對一」關係。 – van