Hi everybody.

After reading the documentation on dictionary based collections at
<http://www.sqlalchemy.org/docs/mappers.html#dictionary-based-collections>, I 
am wondering if I am the only one who things that this code is intuitive:

        item = Item()
        item.notes['color'] = Note('color', 'blue')
        print item.notes['color']

I'd rather write

        item.notes['color'] = Note('blue')

That the key is stored  with the value should be an implementation
detail I think.
I extended sqlalchemy.orm.collections.MappedCollection with a few lines
to implement this (attached).

Shouldn't something like this be included with SQLAlchemy? Or is this a
bad idea?

Greetings, Torsten


-- 
DYNAmore Gesellschaft fuer Ingenieurdienstleistungen mbH
Torsten Landschoff

Office Dresden
Tel: +49-(0)351-4519587
Fax: +49-(0)351-4519561

mailto:torsten.landsch...@dynamore.de
http://www.dynamore.de

Registration court: Mannheim, HRB: 109659, based in Karlsruhe,
Managing director:  Prof. Dr. K. Schweizerhof, Dipl.-Math. U. Franz

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalch...@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

import operator
import sqlalchemy as sa
import sqlalchemy.orm as orm
from sqlalchemy.orm.collections import MappedCollection

class MyMappedCollection(MappedCollection):
    def __init__(self, key_attr):
        super(MyMappedCollection, self).__init__(operator.attrgetter(key_attr))
        self._key_attr = key_attr

    def __setitem__(self, key, value):
        setattr(value, self._key_attr, key)
        if key in self:
            del self[key]
        super(MappedCollection, self).__setitem__(key, value)

def map_on(attr):
    return lambda: MyMappedCollection(attr)

metadata = sa.MetaData()
item_table = sa.Table("item", metadata,
        sa.Column("id", sa.Integer, primary_key=True))

note_table = sa.Table("note", metadata,
        sa.Column("id", sa.Integer, sa.ForeignKey(item_table.c.id), primary_key=True, index=True),
        sa.Column("key", sa.String, primary_key=True),
        sa.Column("value", sa.String),
        sa.Column("desc", sa.String))

class Item(object): pass
class Note(object):
    def __init__(self, **args): self.__dict__.update(args)

orm.mapper(Note, note_table)
orm.mapper(Item, item_table, properties=dict(
        note=orm.relation(Note, cascade="all,delete-orphan", collection_class=map_on("key"))))

engine = sa.create_engine("sqlite:///")
metadata.create_all(engine)
session = orm.sessionmaker(bind=engine)()

item = Item()
item.note["color"] = Note(value="blue", desc="This should be blue because")
item.note["shape"] = Note(value="rectangular")
session.add(item)
session.commit()


Reply via email to