使用sqlAlchemy,我可以拥有一个包含两个类别Address和Customer的系统,其中我有2个关系1用于计费,1个用于发货。这很简单,文档中有一个简单的例子。 如果我决定在类客户中添加所有地址,那么我在类地址中添加一个外键列,我指定地址所属的custumer_id。我无法创建关系,因为它返回以下错误
sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Customer.adresses - 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.
我创建此示例,返回相同的错误
from sqlalchemy import create_engine
from sqlalchemy import Integer, ForeignKey, String, Column
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Customer(Base):
__tablename__ = 'customer'
id = Column(Integer, primary_key=True)
name = Column(String)
billing_address_id = Column(Integer, ForeignKey("address.id"))
shipping_address_id = Column(Integer, ForeignKey("address.id"))
billing_address = relationship("Address", foreign_keys=[billing_address_id])
shipping_address = relationship("Address", foreign_keys=[shipping_address_id])
#until here this is the example vannilla
addresses = relationship("Address")
class Address(Base):
__tablename__ = 'address'
id = Column(Integer, primary_key=True)
street = Column(String)
city = Column(String)
state = Column(String)
zip = Column(String)
#until here this is the example vannila
customer_id = Column(Integer, ForeignKey("customer.id"))
customer = relationship("Customer", foreign_keys=[customer_id], back_populates="addresses")
if __name__ == "__main__":
engine = create_engine('sqlite:///:memory:', echo=True)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
c1 = Customer(name = "customer1")
session.add(c1)
#a1 = Address(street="streetA1", city="cityA1", state="stateA1", zip="zipA1") #this is according the example
a1 = Address(street="streetA1", city="cityA1", state="stateA1", zip="zipA1", customer = c1) #this would be awsome
session.add(a1)
session.commit()
print([x.id for x in session.query(Customer).all()])