SQLAlchemy多态关联

时间:2014-03-24 06:42:51

标签: python sqlalchemy polymorphic-associations

我尝试通过SQLAlchemy库实现多态关联,并使用它作为示例:

discriminator_on_association

但是我的情况有一个不相容。在示例中:创建地址对象,然后将它们添加到供应商或客户(因此,地址表具有供应商和客户表的多态外键以及供应商和客户对象返回地址)。当Address对象添加到这些表时,SQLAlchemy会自动解决如何在表上分配Id的问题。然后可以使用地址的“父”字段获取供应商或客户对象。

虽然在我的情况下我需要首先创建Address对象然后将地址分配给父对象(例如公司,例如它是供应商和客户)。

与我的情况一样使用多态关联的例子:

engine = create_engine('sqlite://', echo=True)
Base.metadata.create_all(engine)

session = Session(engine)

address = Address(street='2569 west elm', city="Detroit", zip="56785")

cust = Customer(name="Tester")
supl = Supplier(company_name="Ace Hammers")

address.parent = supl

session.add_all([address])

session.commit()

但是如果我尝试将此模式应用于我的案例而不进行修改,我会收到下一条错误消息:

Traceback (most recent call last):
  File "discriminator_on_related.py", line 131, in 
    address.parent = supl
  File "C:\Python27\lib\site-packages\sqlalchemy-0.9.3-py2.7-win32.egg\sqlalchemy\ext\associationproxy.py", line 271, in __set__
    setattr(obj, self.target_collection, creator(values))
TypeError: __init__() takes exactly 1 argument (2 given)

我应该如何修改此模式以使其有效?

P.S。对不起,如果这是一个微不足道的问题(SQLAlchemy association_proxy对我来说看起来像某种神奇的东西)。

1 个答案:

答案 0 :(得分:8)

对不起所有在这个问题上烦恼的人。可能答案对某人有用。答案真的太容易了。我的主要错误是我使用复杂的模式示例作为我的案例的基础。要解决此任务,只需要将其拆分为子任务。因此,此任务包括具有连接表的多态继承(使用SQLAlchemy实现非常简单)并在公共(父)表上设置外键。这将显示下一个代码段:

@as_declarative()
class Base(object):
    @declared_attr
    def __tablename__(cls):
        return cls.__name__.lower()
    id = Column(Integer, primary_key=True)


class CompanyInterface(Base):
    discriminator = Column(String)

    __mapper_args__ = {"polymorphic_on": discriminator}


class Address(Base):
    street = Column(String)
    city = Column(String)
    zip = Column(String)
    company_id = Column(Integer, ForeignKey(CompanyInterface.id))
    company = relationship(CompanyInterface)

    def __repr__(self):
        return ("%s(street=%r, city=%r, zip=%r, company=%r)" %
                (self.__class__.__name__, self.street, self.city, self.zip, self.company))


class Customer(CompanyInterface):
    id = Column(Integer, ForeignKey(CompanyInterface.id), primary_key=True)
    name = Column(String)
    __mapper_args__ = {"polymorphic_identity": "Customer"}


class Supplier(CompanyInterface):
    id = Column(Integer, ForeignKey(CompanyInterface.id), primary_key=True)
    company_name = Column(String)
    __mapper_args__ = {"polymorphic_identity": "Supplier"}


engine = create_engine('sqlite:///test/test_me.db', echo=False)
Base.metadata.create_all(engine)

session = Session(engine)

address1 = Address(street='test-1', city="Detroit", zip="56785")
address2 = Address(street='test-2', city="Phoenix", zip="110322")
address3 = Address(street='test-3', city="Washington", zip="432414")

supl1 = Supplier(company_name="Supplier-1 TEST")
supl2 = Supplier(company_name="Supplier-2 TEST")
cust1 = Customer(name="Customer-1 TEST")
cust2 = Customer(name="Customer-2 TEST")

address1.company = supl1
address2.company = cust1
address3.company = cust1

session.add_all([address1, address2, address3])

session.commit()

address3.company = supl2

session.commit()

print "PRINTING, TOTAL = %s" % session.query(Address).count()
for address in session.query(Address):
    print "ADDRESS = %s" % address