I'm searching a way to tell sqlalchemy to map a complex query over some tabes to a custom class MyResult instead of the default RowProxy class. Here's a simple working example
'''
create table foo(id integer, title text);
create table bar(id integer, foo_id integer, name text);
insert into foo values(0, 'null');
insert into foo values(1, 'eins');
insert into bar values(0,0, 'nullnull');
insert into bar values(1,0, 'einsnull');
insert into bar values(2,1, 'zweieins');
'''
and the following code:
from sqlalchemy import *
from itertools import imap
db = create_engine('sqlite:///test.db')
metadata = MetaData(db)
class MyResult(object):
def __init__(self, id, title, name):
self.id = id
self.title = title
self.name = name
foo = Table('foo', metadata, autoload=True)
bar = Table('bar', metadata, autoload=True)
result = select([foo.c.id, foo.c.title, bar.c.name], foo.c.id == bar.c.foo_id).execute().fetchall()
Now I'm looking for a way to tell sqlalchemy to perform a mapping from the result rows to MyResult.
row = result[0]
print type(row)
#<class 'sqlalchemy.engine.base.RowProxy'>
print row.items()
#[(u'id', 0), (u'title', u'null'), (u'name', u'einsnull')]
I know I can do the mapping by hand with something like
my_result = imap(lambda x: MyResult(**x), result)
but I have the feeling that this is not the way to handle it in sqlalchemy.
1-1 relationshipbetween tables, and two combined rows represent one "Object" instance (a-la inheritance); b) single Foo can be referenced by may Bars (1-n relationship). In this case your mapping would not work, as theidcolumn (used as PK) might not be unique. x) are these view-only or would you like to be able to add new DB rows by creating and saving newMyResultinstances?