我正在寻找一种方法来告诉 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 中处理它的方法。
最佳答案
从您的示例中可以看出,Foo.id = 0
将返回 1 个以上的 Foo,这将导致主键的重复值,而主键又将仅导致返回结果集的一个子集。在这种情况下,您可能还应该将 primary_key
扩展到其他 Bar
列(包括 Bar.id
或使用 Bar.name
如果它是唯一的)。
然后你可以使用from_statement
(如 Using Literal SQL 中所述)实现此目的:
sql_qry = select([foo.c.id.label("id"),
foo.c.title.label("title"),
bar.c.name.label("name")],
foo.c.id == bar.c.foo_id)
my_result_qry = session.query(MyResult).from_statement(sql_qry)
for x in my_result_qry.all():
print x
但是,必须映射模型 MyResult
。您可以将它映射到一些虚拟(不存在的)表或 View 。列的 label
也很重要,因为它们必须与类的列定义完全匹配(构造函数将不会被使用)。
关于python - 如何将查询结果映射到 sqlalchemy 中的自定义对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10181427/