简体   繁体   English

无法访问SQLAlchemy查询结果中的别名字段?

[英]Unable to access aliased fields in SQLAlchemy query results?

Confused working with query object results. 与查询对象结果混淆。 I am not using foreign keys in this example. 在此示例中,我没有使用外键。

lookuplocation = aliased(ValuePair)

lookupoccupation = aliased(ValuePair)

persons = db.session.query(Person.lastname, lookuplocation.displaytext, lookupoccupation.displaytext).\
         outerjoin(lookuplocation, Person.location == lookuplocation.valuepairid).\
         outerjoin(lookupoccupation, Person.occupation1 == lookupoccupation.valuepairid).all()

Results are correct as far as data is concerned. 就数据而言,结果是正确的。 However, when I try to access an individual row of data I have an issue: 但是,当我尝试访问单个数据行时,我遇到了一个问题:

persons[0].lastname works as I expected and returns data. person [0] .lastname符合我的预期,并返回数据。

However, there is a person.displaytext in the result but since I aliased the displaytext entity, I get just one result. 但是,结果中有一个person.displaytext,但是由于我为displaytext实体加上了别名,所以我只得到一个结果。 I understand why I get the result but I need to know what aliased field names I would use to get the two displaytext columns. 我知道为什么得到结果,但是我需要知道要用来获取两个displaytext列的别名字段名称。

The actual SQL statement generated by the above join is as follows: 上述联接生成的实际SQL语句如下:

SELECT person.lastname AS person_lastname, valuepair_1.displaytext AS valuepair_1_displaytext, valuepair_2.displaytext AS valuepair_2_displaytext 
FROM person LEFT OUTER JOIN valuepair AS valuepair_1 ON person.location = valuepair_1.valuepairid LEFT OUTER JOIN valuepair AS valuepair_2 ON person.occupation1 = valuepair_2.valuepairid

But none of these "as" field names are available to me in the results. 但是这些“ as”字段名称在结果中都不可用。

I'm new to SqlAlchemy so most likely this is a "newbie" issue. 我是SqlAlchemy的新手,所以很可能是“新手”问题。

Thanks. 谢谢。

Sorry - RTFM issue - should have been: 抱歉-RTFM问题-应该是:

lookuplocation.displaytext.label("myfield1"), lookupoccupation.displaytext.label("myfield2") lookuplocation.displaytext.label(“ myfield1”),lookupoccupation.displaytext.label(“ myfield2”)

After results are returned reference field with person.myfield 返回结果后,使用person.myfield引用字段

Simple. 简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM