gpt4 book ai didi

postgresql - 当数据库中存在表时出现sqlalchemy NoSuchTableError

转载 作者:行者123 更新时间:2023-11-29 12:13:31 33 4
gpt4 key购买 nike

我正在使用 PostgreSQL+Psycopg2,SQLAlchemy。我已经使用 pgAdminIII 工具创建了我的数据库“new_db”,并在其中创建了一个新模式“new_db_schema”。在这个模式下,我有我需要的所有表。我的代码如下所示。

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, String, Integer, Boolean

engine_text = 'postgresql+psycopg2://root:12345@localhost:5432/db_name'
database_engine = create_engine(engine_text, echo = True)

Base = declarative_base(database_engine)

class Some_table(Base):
__tablename__ = 'some_table' # This table exist in database.
__table_args__ = {'autoload':True}

col1 = Column(String, primary_key=True)
col2 = Column(Boolean)

def __init__(self, col1_name, col2_name):
self.col1 = col1_name
self.col2 = col2_name

if __name__ == "__main__":
a = Some_table('blah', 'blah')

现在,当我尝试运行以下代码时,我得到了 sqlalchemy.exc.NoSuchTableError: some_table

因为我已经设置了包含所有表的数据库,所以我想在创建类时自动加载。我在这里错过了什么吗?我需要为数据库中存在的所有表编写此类。任何帮助将不胜感激。

谢谢

最佳答案

您可以:

  • 使用模式限定的表名:__tablename__ = 'new_db_schema.some_table'。你必须在任何地方使用它们:在 ForeignKey 等的字符串参数中。
  • 更改数据库中的 SEARCH_PATH:SET search_path TO new_db_schema;。此 SQL 命令具有 session 范围,因此您必须在使用 SQLAlchemy 事件系统的每个连接开始时发出它。

像这样:

from sqlalchemy import event

def init_search_path(connection, conn_record):
cursor = connection.cursor()
try:
cursor.execute('SET search_path TO new_db_schema;')
finally:
cursor.close()

engine = create_engine('postgresql+psycopg2://...')
event.listen(engine, 'connect', init_search_path)

关于postgresql - 当数据库中存在表时出现sqlalchemy NoSuchTableError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18076515/

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