[英]SQLalchemy not find table for creating foreign key
我在使用 SQL Alchemy 時遇到問題,在嘗試創建數據庫時,我得到:
"sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'estate_agent.person_id' could not find table 'person' with which to generate a foreign key to target column 'id'"
元數據:
db = create_engine('postgresql+psycopg2:...//')
meta = MetaData()
meta.bind = db
人員表:
tbl_person = Table(
'person', meta,
Column('id', Integer, Sequence('seq_person_id'), primary_key=True),
Column('name', String(100), unique=True, nullable = False),
Column('password', String(40), nullable = False),
Column('person_type_id', Integer, ForeignKey("person_type.id"), nullable = False),
Column('register_date', DateTime, default = datetime.now),
Column('pendencies', String(200)),
Column('active', Boolean, default = True),
schema = 'public')
錯誤表:
tbl_estate_agent = Table(
'estate_agent', meta,
Column('person_id', Integer, ForeignKey("person.id"), primary_key = True),
Column('prize_range_id', Integer, ForeignKey("prize_range.id"), nullable = False),
schema = 'public')
正常表(正常創建 fk)
tbl_person_agent = Table(
'person_agent', meta,
Column('person_id', Integer, ForeignKey("person.id"), primary_key = True),
Column('prize_range_id', Integer, ForeignKey("prize_range.id"), nullable = False),
schema = 'public')
創作召喚:
meta.create_all(checkfirst=True)
完整的錯誤日志:
Traceback (most recent call last):
File "database_client.py", line 159, in <module>
meta.create_all(checkfirst=True)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/schema.py", line 3404, in create_all
tables=tables)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1616, in _run_visitor
conn._run_visitor(visitorcallable, element, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1245, in _run_visitor
**kwargs).traverse_single(element)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/visitors.py", line 120, in traverse_single
return meth(obj, **kw)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/ddl.py", line 699, in visit_metadata
collection = [t for t in sort_tables(tables)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/ddl.py", line 862, in sort_tables
{'foreign_key': visit_foreign_key})
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/visitors.py", line 256, in traverse
return traverse_using(iterate(obj, opts), obj, visitors)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/visitors.py", line 247, in traverse_using
meth(target)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/ddl.py", line 853, in visit_foreign_key
parent_table = fkey.column.table File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/util/langhelpers.py", line 725, in __get__
obj.__dict__[self.__name__] = result = self.fget(obj)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/schema.py", line 1720, in column tablekey)
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'estate_agent.person_id' could not find table 'person' with which to generate a foreign key to target column 'id'
解決方案是用實際列替換字符串:
Column('person_id', Integer, ForeignKey(tbl_person.c.id), primary_key=True)
在聲明性的情況下,我通過簡單地導入“無法找到”的類來解決這個問題。
這個異常是因為MetaData實例中沒有父表的記錄,需要在DB中檢索該表。 調用MetaData類的“reflect”函數來獲取 DB 上所有存在的表。 它應該像這樣使用
def upgrade(migrate_engine):
meta.bind = migrate_engine
meta.reflect() # <------ Obtain all tables here.
aggregate_metadata.create()
aggregate_hosts.create()
一個表與另一個有外鍵關聯的表位於不同的文件中。 在這種情況下, sqlalchemy在創建表時會找不到對應的表,如下圖:
sqlalchemy.exc.NoReferencedTableError:與列“aggregate_metadata.aggregate_id”關聯的外鍵找不到表“聚合”,用於生成目標列“id”的外鍵
例如:
# File 002_Add_aggregates_table.py
# ========================================
...
meta = MetaData()
aggregates = Table('aggregates', meta,
...
Column('id', Integer, primary_key=True, nullable=False),
mysql_engine='InnoDB',
mysql_charset='utf8'
)
def upgrade(migrate_engine):
meta.bind = migrate_engine
aggregates.create()
# File 003_Add_aggregate_metadata_hosts.py
# ========================================
...
meta = MetaData()
aggregate_metadata = Table('aggregate_metadata', meta,
...
Column('aggregate_id', Integer, ForeignKey('aggregates.id'), # <------ ForeignKey
nullable=False),
mysql_engine='InnoDB',
mysql_charset='utf8'
)
def upgrade(migrate_engine):
meta.bind = migrate_engine
aggregate_metadata.create()
讓我們定位在拋出異常的點
File "/opt/xxx/.local/lib/python3.6/site-packages/sqlalchemy/util/langhelpers.py", line 1113, in __get__
obj.__dict__[self.__name__] = result = self.fget(obj)
File "/opt/xxx/.local/lib/python3.6/site-packages/sqlalchemy/sql/schema.py", line 2394, in column
tablekey,
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'aggregate_metadata.aggregate_id' could not find table 'aggregates' with which to generate a foreign key to target column 'id'
我們可以找到相應的代碼並進行調試:
# File: sqlalchemy/sql/schema.py
2358 def column(self):
...
2371
2372 if isinstance(self._colspec, util.string_types):
2373
2374 parenttable, tablekey, colname = self._resolve_col_tokens()
# =========> BeginDebug
2375 raise Exception(
2376 'imgrass->\n'
2377 ' - parenttable: %s\n'
2378 ' - parenttable.metadata: %s\n'
2379 ' - tablekey: %s\n'
2380 ' - colname: %s' % (
2381 parenttable,
2382 parenttable.metadata,
2383 tablekey,
2384 colname
2385 )
2386 )
# =========> EndDebug
2387
2388 if tablekey not in parenttable.metadata:
2389 raise exc.NoReferencedTableError(
2390 "Foreign key associated with column '%s' could not find "
2391 "table '%s' with which to generate a "
2392 "foreign key to target column '%s'"
2393 % (self.parent, tablekey, colname),
2394 tablekey,
2395 )
然后我們可以得到以下異常:
Exception: imgrass->
- parenttable: aggregate_metadata
- parenttable.metadata: MetaData(bind=Engine(mysql+pymysql://imgrass:***@172.17.0.1/demo))
- tablekey: aggregates
- colname: id
因此, parenttable.metadata是類MetaData的實例, tablekey是表名。 我們可以合理地猜測表聚合應該包含在類MetaData的實例中。 考慮到這張表的定義在另一個文件中,並且MetaData實例有DB(bind=xxx)的連接方式,所以MetaData類中應該有一個函數來獲取DB中的所有表。
在 MetaData 中,我們可以找到這個函數
# File: sqlalchemy/sql/schema.py
class MetaData(SchemaItem):
...
def reflect(...):
r"""Load all available table definitions from the database.
...
從它的描述中,我們可以猜測它的功能,讓我們將它應用到我的腳本中:
# File 003_Add_aggregate_metadata_hosts.py
# ========================================
...
def upgrade(migrate_engine):
meta.bind = migrate_engine
# ==================> BeginUpdate
meta.reflect()
# ==================> EndUpdate
aggregate_metadata.create()
aggregate_hosts.create()
沒關系!
盡管投票最多的答案解決了這個問題,但用對象替換字符串會迫使您以特定順序定義表(這對於非常大的數據庫來說可能很重要)。 從SQLAlchemy 文檔:
使用字符串的好處是 [不同表] 之間的 in-python 鏈接僅在第一次需要時才被解析,因此表對象可以輕松地分布在多個模塊中並以任何順序定義。
您可以通過將架構傳遞給ForeignKey
繼續使用字符串。 例如,不要這樣做:
tbl_estate_agent = Table(
'estate_agent', meta,
Column('person_id', Integer, ForeignKey("person.id"), primary_key = True),
Column('prize_range_id', Integer, ForeignKey("prize_range.id"), nullable = False),
schema = 'public')
一個可以做到:
tbl_estate_agent = Table(
'estate_agent', meta,
Column('person_id', Integer, ForeignKey("public.person.id"), primary_key = True),
Column('prize_range_id', Integer, ForeignKey("public.prize_range.id"), nullable = False),
schema = 'public')
導入如下的實際類:
from sqlalchemy import Integer, ForeignKey, String, Column
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
並禁止SQLAlchemy警告使用配置中的以下行:
app.config ['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
除此之外,'price_range'表在哪里? 在添加ForeignKey之前添加price_range表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.