2012-03-27 65 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