2012-02-21 84 views
1

我有一个Location类。地点可以有默认的“账单到地址”,这也是地点。我正在使用的字段是CustomerLocation类中的bill_to_idbill_to。为了完整性,我已经包括了父类。如何将一个位置设置为另一个位置的帐单?这种关系应该是一对一的(一个地点只会有一个账单)。不需要backref。SQLAlchemy,同一张表上的一对一关系

TIA

class Location(DeclarativeBase,TimeUserMixin): 
    __tablename__ = 'locations' 

    location_id = Column(Integer,primary_key=True,autoincrement=True) 
    location_code = Column(Unicode(10)) 
    name = Column(Unicode(100)) 
    address_one = Column(Unicode(100)) 
    address_two = Column(Unicode(100)) 
    address_three = Column(Unicode(100)) 
    city = Column(Unicode(100)) 
    state_id = Column(Integer,ForeignKey('states.state_id')) 
    state_relate = relation('State') 
    zip_code = Column(Unicode(100)) 
    phone = Column(Unicode(100)) 
    fax = Column(Unicode(100)) 
    country_id = Column(Integer,ForeignKey('countries.country_id')) 
    country_relate = relation('Country') 
    contact = Column(Unicode(100)) 
    location_type = Column('type',Unicode(50)) 

    __mapper_args__ = {'polymorphic_on':location_type} 

class CustomerLocation(Location): 
    __mapper_args__ = {'polymorphic_identity':'customer'} 
    customer_id = Column(Integer,ForeignKey('customers.customer_id', 
              use_alter=True,name='fk_customer_id')) 
    customer = relation('Customer', 
         backref=backref('locations'), 
         primaryjoin='Customer.customer_id == CustomerLocation.customer_id') 
    tbred_ship_code = Column(Unicode(6)) 
    tbred_bill_to = Column(Unicode(6)) 
    ship_method_id = Column(Integer,ForeignKey('ship_methods.ship_method_id')) 
    ship_method = relation('ShipMethod',primaryjoin='ShipMethod.ship_method_id == CustomerLocation.ship_method_id') 
    residential = Column(Boolean,default=False,nullable=False) 
    free_shipping = Column(Boolean,default=False,nullable=False) 
    collect = Column(Boolean,default=False,nullable=False) 
    third_party = Column(Boolean,default=False,nullable=False) 
    shipping_account = Column(Unicode(50)) 
    bill_to_id = Column(Integer,ForeignKey('locations.location_id')) 
    bill_to = relation('CustomerLocation',remote_side=['locations.location_id']) 

回答

2

见我answer to a related question。通过在表中声明自引用外键,可以在声明中拥有自引用关系,并且可以在声明该类后立即“修补”该类,或者将外部列名指定为字符串而不是类字段。例如:

class Employee(Base): 
    __tablename__ = 'employee' 
    id = Column(Integer, primary_key=True) 
    name = Column(String(64), nullable=False) 
Employee.manager_id = Column(Integer, ForeignKey(Employee.id)) 
Employee.manager = relationship(Employee, backref='subordinates', 
    remote_side=Employee.id) 

我已经成功地利用这一技术为您提供了亲子树的关系(其中一个单亲可以有多个子记录)的两个方向,其前。如果您省略了backref的论点,它可能会或可能不适合您。你总是可以简单地选择在你的应用程序中只使用关系的一个方向。

+0

我无法让它通过字符串工作,但使用您的显式示例发布员工声明,确实有效。谢谢! – jheld 2015-05-27 20:46:56

相关问题