sqlalchemy循环依赖

时间:2012-01-13 20:56:36

标签: python sqlalchemy

我有一个明确的客户和地址。

客户可以包含许多地址。 客户将有一个默认的船舶地址。 客户将有一个默认账单来处理。

customer.locations应该为我提供客户所有地址的列表。

customer.bill_to / ship_to应该给我一个地址。

class Customer(DeclarativeBase):
    __tablename__ = 'customers'
    customer_id = Column(Integer, primary_key=True,autoincrement=True)
    customer_code = Column(Unicode(15),unique=True)
    customer_name = Column(Unicode(100))
    abc_id = Column(Integer,ForeignKey('customer_abc.abc_id'))
    abc = relation(CustomerABC,backref=backref('customers',order_by=customer_code))
    status_id = Column(Integer,ForeignKey('status.status_id'))
    status = relation(Status,backref=backref('customers',order_by=customer_code))
    discount = Column(Float)
    website = Column(Unicode(100))

    bill_to_id = Column(Integer, ForeignKey('addresses.address_id'))
    ship_to_id = Column(Integer, ForeignKey('addresses.address_id'))


    bill_to = relation('CustomerAddress',
                       primaryjoin='CustomerAddress.address_id==Customer.bill_to_id')
    ship_to = relation('CustomerAddress',
                       primaryjoin='CustomerAddress.address_id==Customer.bill_to_id')

    def __init__(self,code,name,status='A',abc='N'):
        self.customer_code = code
        self.customer_name = name
        status = DBSession.query(Status).filter(Status.status_code==status).first()
        if status:
            self.status = status
        abc = DBSession.query(CustomerABC).filter(CustomerABC.abc==abc).first()
        if abc:
            self.abc = abc

class CustomerAddress(DeclarativeBase):
    __tablename__ = 'addresses'
    address_id = Column(Integer,primary_key=True,autoincrement=True)
    address_code = Column(Unicode(10))
    customer_id = Column(Integer,ForeignKey('customers.customer_id'))
    customer = relation('Customer',
                        backref=backref('locations'),
                        primaryjoin='Customer.customer_id == CustomerAddress.customer_id')
    name = Column(Unicode(100))
    address_one = Column(Unicode(100))
    address_two = Column(Unicode(100))
    address_three = Column(Unicode(100))
    city = Column(Unicode(100))
    state = Column(Unicode(100))
    zip_code = Column(Unicode(100))
    phone = Column(Unicode(100))
    fax = Column(Unicode(100))
    country = Column(Unicode(2))
    contact = Column(Unicode(100))
    @property
    def formatted_address(self):
        address = "%s<br/>%s<br/>" %(self.name,self.address_one)
        if self.address_two:
            address += "%s<br/>" %self.address_two
        if self.address_three:
            address += "%s<br/>" %self.address_three
        address += "%s, %s %s" %(self.city,self.state,self.zip_code)
        return address

然而它会抛出......

sqlalchemy.exc.CircularDependencyError: Circular dependency detected:

我只是想了解sqlalchemy的来龙去脉。这page是我开始并尝试扩展的内容。 TIA

1 个答案:

答案 0 :(得分:0)

问题不在模型中,而在于我如何将两条记录添加到会话中。