配置两表间的关系连接

多条连接路径的情况(两表间存在多个外键):

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")
    shipping_address=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)

当直接进行外键关联查询时,会报sqlalchemy.exc.AmbiguousForeignKeysError。

为了解决以上问题,我们可以采用relationship()中的foreign_keys配置参数:

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])

foreign_keys的值可以是某一列或某几列。当然,也可以直接使用字符串,但是字符串必须用双引号引起。如:

billing_address=relationship("Address",foreign_keys="[Customer.billing_address_id]")

配置两表间关系的更多场景见:http://docs.sqlalchemy.org/en/rel_0_9/orm/join_conditions.html

你可能感兴趣的:(配置两表间的关系连接)