繁体   English   中英

SQLAlchemy 歧义外键

[英]SQLAlchemy Ambiguous Foreign Key

我有两个类, UserAddress 一个用户可以有多个地址和一个默认地址。 我试过这个 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM