在我的postgres服務器中,我們有一個database包含 2 個模式的資料庫:public和api.
public有幾個表,我需要創建一個表,api其中有一個表的外鍵public叫做model. 所以是:
-Schemas
--public
---tables
----models
--api
---tables
使用 SQLAlchemy 我有以下課程:
from sqlalchemy import create_engine, MetaData, Table, Column
class __PostgresService:
def __init__(self):
self.__client = create_engine("postgresql://postgres@localhost:5432/database")
metadata = MetaData(self.__client, schema="public")
self.__table = Table("training", metadata,
Column("id", String, primary_key=True, nullable=False),
Column("model_id", ForeignKey("model.id"), nullable=False),
schema="api")
metadata.create_all()
postgres_service = __PostgresService()
但是在啟動時我收到以下錯誤:
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'training.model_id' could not find table 'public.model' with which to generate a foreign key to target column 'id'
它似乎確實在尋找正確的東西,但找不到?我很困惑為什么會發生這種情況,特別是因為錯誤是指找不到“public”,這是默認創建的postgres,而不是我在 pgAdmin 中自己創建的“api”。我是否缺少一些關鍵配置?
uj5u.com熱心網友回復:
您收到的錯誤意味著您正在嘗試創建一個參考 SQLAlchemy 不知道的表的外鍵。您可以通過創建Table與MetaData描述參考表相同的關聯來告訴 sqlalchemy 。您也可以使用 sqlalchemy 的反射功能來做到這一點。例如:
from sqlalchemy import create_engine, MetaData, Table, Column
class __PostgresService:
def __init__(self):
self.__client = create_engine("postgresql://postgres@localhost:5432/database")
metadata = MetaData(self.__client, schema="public")
metadata.reflect(schema="public", only=["model"])
self.__table = Table("training", metadata,
Column("id", String, primary_key=True, nullable=False),
Column("model_id", ForeignKey("model.id"), nullable=False),
schema="api")
metadata.create_all()
postgres_service = __PostgresService()
默認情況下,MetaData.create_all()將在創建表之前首先檢查表是否存在,但您也可以指定要創建的確切表:metadata.create_all(tables=[self.__table])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/348655.html
標籤:Python PostgreSQL sqlalchemy
上一篇:將文本從json轉換為Date
