![](/img/trans.png)
[英]Ambiguous foreign key in self-referencing table [SQLAlchemy/Alembic]
[英]SQLAlchemy Ambiguous Foreign Key
我有兩個類, User
和Address
。 一個用戶可以有多個地址和一個默認地址。 我試過這個 SQLAlchemy 代碼。
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String
from sqlalchemy import ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
engine = create_engine('sqlite:///:memory:', echo=True)
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
default_address_id = Column(Integer, ForeignKey('addresses.id'))
name = Column(String)
fullname = Column(String)
nickname = Column(String)
addresses = relationship("Address", order_by="Address.id", back_populates="user")
class Address(Base):
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
email_address = Column(String, nullable=False)
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship("User", back_populates="addresses")
Base.metadata.create_all(engine)
它導致錯誤
sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship User.addresses - there are multiple foreign key paths linking the tables. Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference to the parent table.
我嘗試將foreign_keys
添加到關系中,但我做對了。
這不是正確的方法,您應該從用戶表的 default_adderess_id 中刪除外鍵。 如果您想區分默認地址和其他地址,您可以在地址表中再增加一個字段作為類型
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.