2

我正在尝试使用 SQLAlchemy 通过双向多对多关系关联两个数据库对象。我需要关联存在于联结表中。表和数据存在于 SQLite3 数据库中。

这是一个简单的例子。

Base = declarative_base()

class Colour (Base):
    __tablename__ = 'colours'
    id = Column("id", Integer, primary_key=True)
    name = Column("name", String)
    vehicles = association_proxy('vehicles_and_colours', 'vehicles')

class Vehicle (Base):
    __tablename__ = 'vehicles'
    id = Column("id", Integer, primary_key=True)
    name = Column("name", String)
    colours = association_proxy('vehicles_and_colours', 'colours')

class ColourVehicle (Base):
    __tablename__ = 'vehicles_and_colours'
    colour_id = Column('colour_fk', Integer, ForeignKey('colours.id'), primary_key=True)
    vehicle_id = Column('vehicle_fk', Integer, ForeignKey('vehicles.id'), primary_key=True)

    colours = relationship(Colour, backref=backref("vehicles_and_colours"))
    vehicles = relationship(Vehicle, backref=backref("vehicles_and_colours"))

blue = session.query(Colour).filter(Colour.name == "blue").first()
car = session.query(Vehicle).filter(Vehicle.name == "car").first()

blue.vehicles.append(car)

这给了我错误:

  File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.8.0b2-py2.6-linux-i686.egg/sqlalchemy/ext/associationproxy.py", line 554, in append
    item = self._create(value)
  File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.8.0b2-py2.6-linux-i686.egg/sqlalchemy/ext/associationproxy.py", line 481, in _create
    return self.creator(value)
TypeError: __init__() takes exactly 1 argument (2 given)

我究竟做错了什么?

4

1 回答 1

3

关联代理要求目标对象具有单参数构造函数,该构造函数将创建适当的中间对象,或者creator指定建立如何创建 ColorVehicle:

vehicles = association_proxy('vehicles_and_colours', 'vehicles', 
                creator=lambda vehicle: ColorVehicle(vehicle=vehicle))

colours = association_proxy('vehicles_and_colours', 'colours', 
               creator=lambda color: ColorVehicle(color=color))

这在以下位置有完整记录:

https://docs.sqlalchemy.org/en/latest/orm/extensions/associationproxy.html#creation-of-new-values

于 2013-02-24T17:42:58.133 回答