My question is about SQLAlchemy but I'm having troubles explaining it in words so I figured I explain it with a simple example of what I'm trying to achieve:
parent = Table('parent', metadata,
Column('parent_id', Integer, primary_key=True),
Column('name', Unicode),
)
parent_child = Table('parent_child', metadata,
Column('parent_id', Integer, primary_key=True),
Column('child_id', Integer, primary_key=True),
Column('number', Integer),
ForeignKeyConstraint(['parent_id'], ['parent.parent_id']),
ForeignKeyConstraint(['child_id'], ['child.child_id']),
)
child = Table('child', metadata,
Column('child_id', Integer, primary_key=True),
Column('name', Unicode),
)
class Parent(object):
pass
class ParentChild(object):
pass
class Child(object):
pass
>>> p = Parent(name=u'A')
>>> print p.children
{}
>>> p.children[0] = Child(name=u'Child A')
>>> p.children[10] = Child(name=u'Child B')
>>> p.children[10] = Child(name=u'Child C')
This code would create 3 rows in parent_child table, column number would be 0 for the first row, and 10 for the second and third row.
>>> print p.children
{0: [<Child A>], 10: [<Child B>, <Child C>]}
>>> print p.children[10][0]
<Child B>
(I left out all SQLAlchemy session/engine code in the example to make it as clean as possible)
I did a try using´
collection_class=attribute_mapped_collection('number')
on a relation between Parent and ParentChild, but it only gave me one child for each number. Not a dict with lists in it. Any help appreciated!
UPDATED!
Thanks to Denis Otkidach I now has this code, but it still doesn't work.
def _create_children(number, child):
return ParentChild(parent=None, child=child, number=number)
class Parent(object):
children = association_proxy('_children', 'child', creator=_create_children)
class MyMappedCollection(MappedCollection):
def __init__(self):
keyfunc = lambda attr_name: operator.attrgetter('number')
MappedCollection.__init__(self, keyfunc=keyfunc)
@collection.appender
@collection.internally_instrumented
def set(self, value, _sa_initiator=None):
key = self.keyfunc(value)
try:
self.__getitem__(key).append(value)
except KeyError:
self.__setitem__(key, [value])
mapper(Parent, parent, properties={
'_children': relation(ParentChild, collection_class=MyMappedCollection),
})
To insert an Child seems to work
p.children[100] = Child(...)
But when I try to print children like this:
print p.children
I get this error:
sqlalchemy.orm.exc.UnmappedInstanceError: Class '__builtin__.list' is not mapped