Sqlalchemy和python的受限关键字

时间:2019-04-29 12:46:41

标签: python python-3.x sqlalchemy

预先存在的db和sqlalchemy。使用反射我想查询这样的数据库,但是有一个问题。表称为“日志”,它具有两个均引用表“ server”的外键。表服务器具有名为“ class”的列,并且该名称在python中受到限制。

代码:

from sqlalchemy import orm, create_engine
from sqlalchemy.ext.automap import automap_base
from django.conf import settings


base = automap_base()

connection_setup = (
    "{driver}://{user}:{password}@{host}:{port}/{dbname}".format(
        **settings.ALCHEMY_DB))

engine = create_engine(connection_setup, echo=False)

base.prepare(engine, reflect=True)

scoped_session = orm.scoped_session(orm.sessionmaker(bind=engine))

session = scoped_session()

logs = base.classes.logs
server = base.classes.server

local_server = orm.aliased(server, name='local_server')
remote_server = orm.aliased(server, name='remote_server')

query = (
    session
    .query(
        logs, local_server.class, remote_server.class)
    .outerjoin(
        local_server, logs.local_server_id == local_server.id
    )
    .outerjoin(
        remote_server, logs.remte_server_id == remote_server.id
    )
)

rows = query.all()

例外:

  File "ff.py", line 29
      logs, local_server.class, remote_server.class)
                                              ^
SyntaxError: invalid syntax

如何解决此类问题?

1 个答案:

答案 0 :(得分:2)

可能是最简单的解决方案:

getattr(local_server, 'class')

或者可以显式覆盖列:

https://docs.sqlalchemy.org/en/13/orm/extensions/automap.html#specifying-classes-explicitly

尝试并测试了两者。