gpt4 book ai didi

python-3.x - Postgres SQLalchemy automap 无法识别关系

转载 作者:行者123 更新时间:2023-11-29 13:44:26 30 4
gpt4 key购买 nike

按照 sqlalchemy documentation and adapting 中的示例,我的数据库有这段代码:

from sqlalchemy.ext.automap import automap_base
from sqlalchemy import create_engine, MetaData

engine = create_engine('postgresql://u:pw@db')

metadata = MetaData(schema='name')
metadata.reflect(engine, only=['a', 'b'])

Base = automap_base(bind=engine, metadata=metadata)
Base.prepare()

A, B = Base.classes.a, Base.classes.b

result = A.first()

print(result.id)

运行脚本返回此错误:

File "/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile
execfile(filename, namespace)

File "/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "/Users/<User>/untitled0.py", line 18, in <module>
Base.prepare(engine,reflect=True)

File "/anaconda3/lib/python3.6/site-packages/sqlalchemy/ext/automap.py", line 788, in prepare
generate_relationship)

File "/anaconda3/lib/python3.6/site-packages/sqlalchemy/ext/automap.py", line 895, in _relationships_for_fks
local_cls, referred_cls):

TypeError: issubclass() arg 2 must be a class or tuple of classes

最佳答案

由于可以在没有模式的情况下识别表,因此消除限制然后使用元数据在没有声明基础的情况下自动映射。

以下是相关 sqlalchemy 文档的链接:

  1. create_engine

  2. MetaData

  3. Table

  4. select

    from sqlalchemy import create_engine, MetaData, Table, select

    engine = create_engine('postgresql://u:pw@db')

    metadata = MetaData(engine)

    a = Table('a', metadata, autoload=True, autoload_with=engine)
    b = Table('b', metadata, autoload=True, autoload_with=engine)

    ab = a.join(b)

    query = select([a.c.id,b.c.id]).select_from(ab)

    result = conn.execute(query).fetchone()

运行此脚本将返回表 a 的第一条记录和表 b 的第一条连接记录。

请注意,此格式完全依赖于两个表之间具有外键连接的数据库。此外,在大多数编辑器中,使用这些类将为您提供 table.fields 的代码完成,而此方法不会。

关于python-3.x - Postgres SQLalchemy automap 无法识别关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50803680/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com