且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将查询结果映射到sqlalchemy中的自定义对象?

更新时间:2023-02-01 09:49:06

从您的示例可以看出,Foo.id = 0返回的Foo超过1,这将导致主键的值重复,反过来,这只会导致返回结果集的子集.在这种情况下,您可能还应该将primary_key扩展到其他Bar列(包括Bar.id或使用Bar.name(如果唯一)).

As can be seen from your sample, there will be more than 1 Foo returned for Foo.id = 0, which will result in the duplicate value for the primary key, which will in turn only result in a subset of your result-set being returned. In this case you probably should extend the primary_key also to other Bar columns (either include Bar.id or use Bar.name if it is unique).

然后,您可以使用 from_statement (如使用文字SQL )来实现:

Then you can use the from_statement (as documented in Using Literal SQL) to achieve this:

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.您可以将其映射到某个虚拟(不存在)的表或视图.列的label也是很重要的,因为它们必须与您对类的列定义完全匹配(无论如何,构造器将使用)

However, the model MyResult has to be mapped. You can map it to some dummy (non-existant) table or view. Also the labels for columns are important as they must exactly match your column definitions of the class (the constructor will not be used anyways).