Associate objects in a many-to-many relationship i

2020-02-15 02:47发布

I'm trying to associate two database objects via a bidirectional many-to-many relationship using SQLAlchemy. I need the association to exist in a junction table. The tables and data exist in a SQLite3 database.

Here's a simple example.

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)

This gives me the error:

  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)

What am I doing wrong?

1条回答
姐就是有狂的资本
2楼-- · 2020-02-15 03:32

the association proxy requires either that target object has a single-argument constructor which will create the appropriate intermediary object, or that creator is specified which establishes how to create a 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))

this is fully documented at:

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

查看更多
登录 后发表回答