我尝试在SQLAlchemy文档上测试有关处理多个连接路径的代码示例。但是,在创建客户对象后,两个关系属性都是None。我想知道如何正确处理多个连接路径?我是否还需要在Address类中创建关系?我什么时候需要使用back_populates?
from sqlalchemy import create_engine
from sqlalchemy import Integer, ForeignKey, String, Column
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
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])
class Address(Base):
__tablename__ = 'address'
id = Column(Integer, primary_key=True)
street = Column(String)
city = Column(String)
state = Column(String)
zip = Column(String)
engine = create_engine('sqlite:///Testing.db')
Base.metadata.create_all(engine)
a1 = Address(street="a street", city="a city", state="A", zip="12345")
a2 = Address(street="b street", city="b city", state="B", zip="1233")
c1 = Customer(name="Jack")
print(c1.billing_address)
答案 0 :(得分:1)
如果您不需要,Address
中的关系不是必需的。 back_populates=
用于将两个关系明确地链接在一起,或者正如文档所述,"establish “bidirectional” behavior between each other"。
您的客户和地址未链接的原因是您从未链接过它们。在施工期间将地址传递给客户或之后进行设置:
c1 = Customer(name="Jack", billing_address=a1)
c1.shipping_address = a2
现在,当您向会话添加c1
并提交时,SQLAlchemy将按正确的顺序处理a1
,a2
和c1
的插入,以便它可以填写c1
的外键属性。发生这种情况是因为默认情况下relationship()
启用了save-update
级联,这会将关联的对象放置到会话中。