Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- adresses = 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="adresses")
- 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()])
- #error : 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.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement