【问题标题】:Associate objects in a many-to-many relationship in SQLAlchemy在 SQLAlchemy 中以多对多关系关联对象
【发布时间】:2018-10-28 05:42:41
【问题描述】:

我正在尝试使用 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)

我做错了什么?

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    关联代理要求目标对象有一个单参数构造函数来创建适当的中间对象,或者指定 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

    【讨论】:

      猜你喜欢
      • 2015-03-16
      • 1970-01-01
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 2017-08-30
      相关资源
      最近更新 更多