具有关联对象的多对多和定义的所有关系在删除时崩溃

Many-to-Many with association object and all relationships defined crashes on delete

当具有描述了所有关系的完全成熟的多对多时,删除两个主要对象之一会崩溃。

描述

汽车 (.car_ownerships) <-> (.car) 汽车所有权 (.person ) <-> (.car_ownerships)

汽车 (.people) <----------------> (.cars)

问题

删除汽车时 SA首先删除关联对象CarOwnership(因为'through'与secondary参数的关系),然后尝试将同一个关联中的外键更新为NULL对象,因此崩溃。

我该如何解决?我有点困惑地看到文档中没有解决这个问题,也没有在我可以在网上找到的任何地方解决,因为我认为这种模式很常见:-/。我错过了什么?

我知道我可以为直通关系打开 passive_deletes 开关,但我想保留删除语句,只是为了防止更新发生或(让它发生之前)。

编辑:实际上,如果session中加载了依赖对象,passive_deletes并不能解决问题,因为DELETE语句仍然会被发出.一个解决方案是使用 viewonly=True,但我不仅失去了删除,而且失去了关联对象的自动创建。另外我觉得 viewonly=True 很危险,因为它让你 append() 不用坚持!

REPEX

设置

from sqlalchemy import create_engine, Table, Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref, sessionmaker

engine = create_engine('sqlite:///:memory:', echo = False)
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()


class Person(Base):
    __tablename__ = 'persons'

    id = Column(Integer(), primary_key=True)
    name = Column(String(255))

    cars = relationship('Car', secondary='car_ownerships', backref='people')

    def __repr__(self):
        return '<Person {} [{}]>'.format(self.name, self.id)

class Car(Base):
    __tablename__ = 'cars'

    id = Column(Integer(), primary_key=True)
    name = Column(String(255))

    def __repr__(self):
        return '<Car {} [{}]>'.format(self.name, self.id)


class CarOwnership(Base):
    __tablename__ = 'car_ownerships'

    id = Column(Integer(), primary_key=True)
    type = Column(String(255))
    car_id = Column(Integer(), ForeignKey(Car.id))
    car = relationship('Car', backref='car_ownerships')
    person_id = Column(Integer(), ForeignKey(Person.id))
    person = relationship('Person', backref='car_ownerships')

    def __repr__(self):
        return 'Ownership [{}]: {} <<-{}->> {}'.format(self.id, self.car, self.type, self.person)

Base.metadata.create_all(engine)

归档对象

antoine = Person(name='Antoine')
rob = Person(name='Rob')
car1 = Car(name="Honda Civic")
car2 = Car(name='Renault Espace')

CarOwnership(person=antoine, car=car1, type = "secondary")
CarOwnership(person=antoine, car=car2, type = "primary")
CarOwnership(person=rob, car=car1, type = "primary")

session.add(antoine)
session.commit()

session.query(CarOwnership).all()

正在删除 -> 崩溃

print('#### DELETING')
session.delete(car1)
print('#### COMMITING')
session.commit()


# StaleDataError                            Traceback (most recent call last)
# <ipython-input-6-80498b2f20a3> in <module>()
#       1 session.delete(car1)
# ----> 2 session.commit()
# ...

诊断

我在上面提出的解释得到了引擎给出的 SQL 语句的支持 echo=True:

#### DELETING
#### COMMITING
2016-07-07 16:55:28,893 INFO sqlalchemy.engine.base.Engine SELECT persons.id AS persons_id, persons.name AS persons_name 
FROM persons, car_ownerships 
WHERE ? = car_ownerships.car_id AND persons.id = car_ownerships.person_id
2016-07-07 16:55:28,894 INFO sqlalchemy.engine.base.Engine (1,)
2016-07-07 16:55:28,895 INFO sqlalchemy.engine.base.Engine SELECT car_ownerships.id AS car_ownerships_id, car_ownerships.type AS car_ownerships_type, car_ownerships.car_id AS car_ownerships_car_id, car_ownerships.person_id AS car_ownerships_person_id 
FROM car_ownerships 
WHERE ? = car_ownerships.car_id
2016-07-07 16:55:28,896 INFO sqlalchemy.engine.base.Engine (1,)
2016-07-07 16:55:28,898 INFO sqlalchemy.engine.base.Engine DELETE FROM car_ownerships WHERE car_ownerships.car_id = ? AND car_ownerships.person_id = ?
2016-07-07 16:55:28,898 INFO sqlalchemy.engine.base.Engine ((1, 1), (1, 2))
2016-07-07 16:55:28,900 INFO sqlalchemy.engine.base.Engine UPDATE car_ownerships SET car_id=? WHERE car_ownerships.id = ?
2016-07-07 16:55:28,900 INFO sqlalchemy.engine.base.Engine ((None, 1), (None, 2))
2016-07-07 16:55:28,901 INFO sqlalchemy.engine.base.Engine ROLLBACK

编辑

使用association_proxy

我们可以使用关联代理来尝试实现 'through' 关系。

然而,为了直接.append()一个依赖对象,我们需要为关联对象创建一个构造函数。此构造函数必须 'hacked' 才能成为双向的,因此我们可以同时使用两个赋值:

my_car.people.append(Person(name='my_son'))
my_husband.cars.append(Car(name='new_shiny_car'))

生成的(经过中间测试的)代码如下,但我对它不太满意(因为这个 hacky 构造函数还有什么会破坏?)。

编辑: 下面的 RazerM 的回答中介绍了使用关联代理的方法。 association_proxy() 有一个 creator 参数,它减轻了我最终在下面使用的巨大构造函数的需要。

class Person(Base):
    __tablename__ = 'persons'

    id = Column(Integer(), primary_key=True)
    name = Column(String(255))

    cars = association_proxy('car_ownerships', 'car')

    def __repr__(self):
        return '<Person {} [{}]>'.format(self.name, self.id)

class Car(Base):
    __tablename__ = 'cars'

    id = Column(Integer(), primary_key=True)
    name = Column(String(255))

    people = association_proxy('car_ownerships', 'person')

    def __repr__(self):
        return '<Car {} [{}]>'.format(self.name, self.id)


class CarOwnership(Base):
    __tablename__ = 'car_ownerships'

    id = Column(Integer(), primary_key=True)
    type = Column(String(255))
    car_id = Column(Integer(), ForeignKey(Car.id))
    car = relationship('Car', backref='car_ownerships')
    person_id = Column(Integer(), ForeignKey(Person.id))
    person = relationship('Person', backref='car_ownerships')

    def __init__(self, car=None, person=None, type='secondary'):
        if isinstance(car, Person):
            car, person = person, car
        self.car = car
        self.person = person
        self.type = type        

    def __repr__(self):
        return 'Ownership [{}]: {} <<-{}->> {}'.format(self.id, self.car, self.type, self.person)

您使用的是 Association Object,因此您需要采取不同的方式。

我改变了这里的关系,仔细看它们,因为一开始你有点难以理解(至少对我来说是这样!)。

我使用了 back_populates,因为在这种情况下它比 backref 更清晰。多对多关系的双方都必须直接引用 CarOwnership,因为这是您要使用的对象。这也是您的示例显示的内容;您需要使用它,以便您可以设置 type.

class Person(Base):
    __tablename__ = 'persons'

    id = Column(Integer(), primary_key=True)
    name = Column(String(255))

    cars = relationship('CarOwnership', back_populates='person')

    def __repr__(self):
        return '<Person {} [{}]>'.format(self.name, self.id)


class Car(Base):
    __tablename__ = 'cars'

    id = Column(Integer(), primary_key=True)
    name = Column(String(255))

    people = relationship('CarOwnership', back_populates='car')

    def __repr__(self):
        return '<Car {} [{}]>'.format(self.name, self.id)


class CarOwnership(Base):
    __tablename__ = 'car_ownerships'

    id = Column(Integer(), primary_key=True)
    type = Column(String(255))
    car_id = Column(Integer(), ForeignKey(Car.id))
    person_id = Column(Integer(), ForeignKey(Person.id))

    car = relationship('Car', back_populates='people')
    person = relationship('Person', back_populates='cars')

    def __repr__(self):
        return 'Ownership [{}]: {} <<-{}->> {}'.format(self.id, self.car, self.type, self.person)

请注意,删除任一侧后,car_ownerships 行不会被删除,它只会将外键设置为 NULL。如果您想设置自动删除,我可以在我的答案中添加更多内容。

编辑:直接访问CarPerson对象的集合,需要使用association_proxy,类 然后改成这样:

from sqlalchemy.ext.associationproxy import association_proxy

class Person(Base):
    __tablename__ = 'persons'

    id = Column(Integer(), primary_key=True)
    name = Column(String(255))

    cars = association_proxy(
        'cars_association', 'car', creator=lambda c: CarOwnership(car=c))

    def __repr__(self):
        return '<Person {} [{}]>'.format(self.name, self.id)


class Car(Base):
    __tablename__ = 'cars'

    id = Column(Integer(), primary_key=True)
    name = Column(String(255))

    people = association_proxy(
        'people_association', 'person', creator=lambda p: CarOwnership(person=p))

    def __repr__(self):
        return '<Car {} [{}]>'.format(self.name, self.id)


class CarOwnership(Base):
    __tablename__ = 'car_ownerships'

    id = Column(Integer(), primary_key=True)
    type = Column(String(255), default='secondary')
    car_id = Column(Integer(), ForeignKey(Car.id))
    person_id = Column(Integer(), ForeignKey(Person.id))

    car = relationship('Car', backref='people_association')
    person = relationship('Person', backref='cars_association')

    def __repr__(self):
        return 'Ownership [{}]: {} <<-{}->> {}'.format(self.id, self.car, self.type, self.person)

编辑: 在您的编辑中,您在将其转换为使用 backref 时犯了一个错误。您的汽车和人的关联代理不能同时使用 'car_ownerships' 关系,这就是为什么我有一个名为 'people_association' 和一个名为 'cars_association'.

的原因

您拥有的 'car_ownerships' 关系与关联 table 被称为 'car_ownerships' 这一事实无关,因此我以不同的方式命名它们。

我修改了上面的代码块。要允许附加工作,您需要将创建者添加到关联代理。我已将 back_populates 更改为 backref,并将默认 type 添加到 Column 对象而不是构造函数。

最干净的解决方案如下,不涉及关联代理。它是完全成熟的多对多关系所缺少的秘诀。

在这里,我们编辑从依赖对象 CarPerson 到关联对象 的直接关系CarOwnership,为了防止这些关系在关联对象被删除后发出UPDATE。为此,我们使用 passive_deletes='all' 标志。

产生的互动是:

  • 能够从依赖对象查询和设置关联对象
    # Changing Ownership type:
    my_car.car_ownerships[0].type = 'primary'
    # Creating an ownership between a car and a person directly:
    CarOwnership(car=my_car, person=my_husband, type='primary')
  • 直接访问和编辑依赖对象的能力:

    # Get all cars from a person:
    [print(c) for c in my_husband.cars]
    # Update the name of one of my cars:
    me.cars[0].name = me.cars[0].name + ' Cabriolet'
    
  • 创建或删除依赖对象时自动创建和删除关联对象

    # Create a new owner and assign it to a car:
    my_car.people.append(Person('my_husband'))
    session.add(my_car)
    session.commit() # Creates the necessary CarOwnership
    # Delete a car:
    session.delete(my_car)
    session.commit() # Deletes all the related CarOwnership objects
    

代码

class Person(Base):
    __tablename__ = 'persons'

    id = Column(Integer(), primary_key=True)
    name = Column(String(255))

    cars = relationship('Car', secondary='car_ownerships', backref='people')

    def __repr__(self):
        return '<Person {} [{}]>'.format(self.name, self.id)

class Car(Base):
    __tablename__ = 'cars'

    id = Column(Integer(), primary_key=True)
    name = Column(String(255))

    def __repr__(self):
        return '<Car {} [{}]>'.format(self.name, self.id)


class CarOwnership(Base):
    __tablename__ = 'car_ownerships'

    id = Column(Integer(), primary_key=True)
    type = Column(String(255))
    car_id = Column(Integer(), ForeignKey(Car.id))
    car = relationship('Car', backref=backref('car_ownerships', passive_deletes='all'))
    person_id = Column(Integer(), ForeignKey(Person.id))
    person = relationship('Person', backref=backref('car_ownerships', passive_deletes='all'))

    def __repr__(self):
        return 'Ownership [{}]: {} <<-{}->> {}'.format(self.id, self.car, self.type, self.person)