我正在寻找一种方法告诉sqlalchemy将一些选项卡上的复杂查询映射到自定义类MyResult
,而不是默认的RowProxy
类。下面是一个简单的工作示例
'''
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');
'''
以及以下代码:
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()
现在我正在寻找一种方法来告诉sqlalchemy执行从结果行到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')]
我知道我可以手工绘制地图
my_result = imap(lambda x: MyResult(**x), result)
但我感觉这不是用sqlalchemy处理它的方法。
通过直接调用} 。正如您所拥有的,
select
,您将忽略ORM特性。您需要在MyResult
类上使用^{MyResult
只是一个普通的类。像这样的:
从您的示例中可以看到,
Foo.id = 0
将返回多个Foo,这将导致主键的值重复,而主键只返回结果集的一个子集。在这种情况下,您可能还应该将primary_key
扩展到其他Bar
列(包括Bar.id
或使用Bar.name
,如果它是唯一的)。然后,您可以使用^{} (如Using Literal SQL中所述)来实现这一点:
但是,必须映射模型
MyResult
。您可以将它映射到某个虚拟(不存在的)表或视图。此外,列的label
也很重要,因为它们必须与类的列定义完全匹配(构造函数无论如何都不会使用)。相关问题 更多 >
编程相关推荐