I am creating a Collection class using the OrderedDict and
MappedCollection with primary key id as the key index.  The problem,
as noted in the docs, is that the key should be an immutable field.
Since I am using a primary key, the value will change when I am
instantiating a new object and adding it to the collection.  The code
illustrates my concept:

class Collection(OrderedDict, MappedCollection):
   def __init__(self, *args, **kwargs):
      MappedCollection.__init__(self, keyfunc=lambda item: item.id)
      OrderedDict.__init__(self, *args, **kwargs)

    def refresh(self, *args, **kwargs):
        """ Updates all keys based on the keyfunc and each current
value"""
        dict_copy = self.copy()
        self.clear()
        for item in dict_copy.values():
            MappedCollection.set(self, item)


class Parent(Base): pass

class Child(Base): pass

session.mapper(class_=Child, local_table=child_table)

session.mapper(class_=Parent, local_table=parent_table,
               properties={'childs':relation(Child, backref='parent',
collection_class=ChildCollection)})


some_collection = ChildCollection()
new_child = Child(id=None, data='foo')
some_collection.set(new_child) # key is None, id is None

session.save(some_collection.values()) # save the child

# at this point, key is still None, but id is 1

some_collection.refresh() # key will be 1.
# I would like the refresh behavior to be invoked during/after a
flush.


Now, if I saved the Child under the Parent, then the key index would
have been updated automatically like so:
my_parent = Parent
Parent.childs.set(new_child)
session.save(Parent)
# The childs index will be 1
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to