From e44857977a79e306808e9e56638d6ca339b983a4 Mon Sep 17 00:00:00 2001 From: Mike Bayer Date: Wed, 11 Apr 2007 21:15:11 +0000 Subject: [PATCH] [ticket:534] get dictionary append() method properly --- lib/sqlalchemy/orm/attributes.py | 4 +++- test/orm/relationships.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/lib/sqlalchemy/orm/attributes.py b/lib/sqlalchemy/orm/attributes.py index b7d2050ffb..699a2f8875 100644 --- a/lib/sqlalchemy/orm/attributes.py +++ b/lib/sqlalchemy/orm/attributes.py @@ -396,7 +396,9 @@ class InstrumentedList(object): self._data_appender = self.data.add self._clear_data = self._clear_set elif isinstance(self.data, dict): - if not hasattr(self.data, 'append'): + if hasattr(self.data, 'append'): + self._data_appender = self.data.append + else: raise exceptions.ArgumentError("Dictionary collection class '%s' must implement an append() method" % type(self.data).__name__) self._clear_data = self._clear_dict else: diff --git a/test/orm/relationships.py b/test/orm/relationships.py index e2ca39c511..fac484975d 100644 --- a/test/orm/relationships.py +++ b/test/orm/relationships.py @@ -716,6 +716,34 @@ class CustomCollectionsTest(testbase.ORMTest): sess.clear() f = sess.query(Foo).get(f.col1) assert len(list(f.bars)) == 2 + f.bars.clear() + + def testdict(self): + """test that a 'dict' can be used as a collection and can lazyload.""" + class Foo(object): + pass + class Bar(object): + pass + class AppenderDict(dict): + def append(self, item): + self[id(item)] = item + def __iter__(self): + return iter(self.values()) + + mapper(Foo, sometable, properties={ + 'bars':relation(Bar, collection_class=AppenderDict) + }) + mapper(Bar, someothertable) + f = Foo() + f.bars.append(Bar()) + f.bars.append(Bar()) + sess = create_session() + sess.save(f) + sess.flush() + sess.clear() + f = sess.query(Foo).get(f.col1) + assert len(list(f.bars)) == 2 + f.bars.clear() class ViewOnlyTest(testbase.ORMTest): """test a view_only mapping where a third table is pulled into the primary join condition, -- 2.47.2