2012-03-27 63 views
4

嘗試使用association_proxy時出現錯誤。與0-n關係的Association_proxy

我被映射到A級,其中0-n的關係B. B已經0-n的關係下的association_proxy是訪問一個從C

class C(base): 
    a = association_proxy('b', 'a') 

它的工作原理沒有問題,如果它真的與B有關係。但是如果這個關係是null,那麼試圖訪問myCinstance.a將會拋出:AttributeError 'NoneType' object has no attribute 'a'。 我想它適用於1-n關係,但有沒有辦法讓myCinstance.a返回None而不是錯誤? (我看到了創造者的選擇,但看起來只是爲了設置,沒有得到)。

在此先感謝。

我使用SQLAlchemy的0.7.5

編輯:我想出了一個簡單的例子,從閱讀http://docs.sqlalchemy.org/en/latest/orm/extensions/associationproxy.html#querying-with-association-proxies,當你發出的情況下的處理說明問題https://gist.github.com/2225046

+0

這是不是http://stackoverflow.com/questions/9063478/how-to-的副本extend-the-getter-functional-of-sqlalchemys-association-proxy? – 2012-03-28 08:55:39

+0

它將適用於我的一個用例(訪問myCinstance.a)。但我不能過濾查詢,如'.query(C).filter(C.a == ...)' – tonio 2012-03-28 09:01:21

回答

7

我相信查詢(即SQL使用EXISTS子句來捕獲不存在的B問題)。

爲了得到存取快捷方式工作,你需要使用getset_factory參數:

def outer_join_accessor_factory(collection_type, proxy): 
    def getter(obj): 
     if obj is None: 
      return None 
     return getattr(obj, proxy.value_attr) 
    def setter(obj, value): 
     setattr(obj, proxy.value_attr, value) 
    return getter, setter 

class C(Base): 
    __tablename__ = 'c' 
    id = Column(Integer, primary_key=True) 
    id_b = Column(Integer, ForeignKey('b.id')) 
    b = relationship('B', backref='cs') 
    a = association_proxy('b', 'a', getset_factory=outer_join_accessor_factory) 
+0

非常感謝! – tonio 2012-03-28 10:01:15

+0

也是getset_factory的一個很好的例子,因爲SQLAlchemy缺少這個部分。 – 2012-06-26 14:11:46