3

我有一些 sqlalchemy 查询:

>>> items = (
    Company.query
    .add_column(Address.city)
    .join(Company.address)
    .filter(and_(
        ...some filters...
    ))
    .all()
)
>>> items
[(Company(6239), Berlin), (Company(5388), Moscow), ...]

如何修改我的查询,将 Address.city 放入实体公司?我希望它看起来像:

...
>>> items
[Company(6239), Company(5388), ...]
>>> items[0].city
Berlin

谢谢你。

4

1 回答 1

4

我认为您不能在不修改模型的情况下直接在查询中执行此操作。
但是您可以在代码中轻松实现这一点:

>>> items
[(Company(6239), Berlin), (Company(5388), Moscow), ...]

>>> # set company
>>> for (_company, _city) in items:
        _company.city = _city
>>> # remove city attribute
>>>> items = [_company for (_company, _city) in items]

>>> items
[Company(6239), Company(5388), ...]
>>> items[0].city
Berlin
于 2012-07-04T15:17:39.240 回答