Association_proxy with 0-n relations

I got an error while trying to use associative proxy.

I got a mapped class A, with a ratio of 0-n to B. B has a relationship of 0-n to C. Connection_proxy must access A from C.

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

It works without problems, if it really is related to B. But if this relation is null , then trying to access myCinstance.a throws a: AttributeError 'NoneType' object has no attribute 'a' . I think this works well with the 1-n ratio, but is there a way myCinstance.a returns None instead of an error? (I saw the creator option, but it only looks for customization, not for getting).

Thanks in advance.

Im using SqlAlchemy 0.7.5

EDIT : I came up with a simple example describing the problem https://gist.github.com/2225046

+4
source share
1 answer

I believe that when reading http://docs.sqlalchemy.org/en/latest/orm/extensions/associationproxy.html#querying-with-association-proxies the thing is processed when the query is issued (i.e. SQL uses the EXISTS clause, to catch a non-existent question B).

To access the access shortcut, you need to use the getset_factory argument:

 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) 
+7
source

Source: https://habr.com/ru/post/1403692/


All Articles