Advertisement
Guest User

Untitled

a guest
Apr 26th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.10 KB | None | 0 0
  1. from sqlalchemy import create_engine
  2. from sqlalchemy import Integer, ForeignKey, String, Column
  3. from sqlalchemy.ext.declarative import declarative_base
  4. from sqlalchemy.orm import relationship
  5. from sqlalchemy.orm import sessionmaker
  6.  
  7. Base = declarative_base()
  8.  
  9. class Customer(Base):
  10.     __tablename__ = 'customer'
  11.     id = Column(Integer, primary_key=True)
  12.     name = Column(String)
  13.  
  14.     billing_address_id = Column(Integer, ForeignKey("address.id"))
  15.     shipping_address_id = Column(Integer, ForeignKey("address.id"))
  16.     billing_address = relationship("Address", foreign_keys=[billing_address_id])
  17.     shipping_address = relationship("Address", foreign_keys=[shipping_address_id])
  18.     #until here this is the example vannilla
  19.     adresses = relationship("Address")
  20.  
  21. class Address(Base):
  22.     __tablename__ = 'address'
  23.     id = Column(Integer, primary_key=True)
  24.     street = Column(String)
  25.     city = Column(String)
  26.     state = Column(String)
  27.     zip = Column(String)
  28.     #until here this is the example vannila
  29.     customer_id = Column(Integer, ForeignKey("customer.id"))
  30.     customer = relationship("Customer", foreign_keys=[customer_id], back_populates="adresses")
  31.  
  32.  
  33. if __name__ == "__main__":
  34.     engine = create_engine('sqlite:///:memory:', echo=True)
  35.     Base.metadata.create_all(engine)
  36.     Session = sessionmaker(bind=engine)
  37.     session = Session()
  38.     c1 = Customer(name = "customer1")
  39.     session.add(c1)
  40.     #a1 = Address(street="streetA1", city="cityA1", state="stateA1", zip="zipA1") #this is according the example
  41.     a1 = Address(street="streetA1", city="cityA1", state="stateA1", zip="zipA1", customer = c1) #this would be awsome
  42.     session.add(a1)
  43.     session.commit()
  44.  
  45.     print([x.id for x in session.query(Customer).all()])
  46.  
  47. #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