【问题标题】:Many-to-Many with association object and all relationships defined crashes on delete具有关联对象的多对多和定义的所有关系在删除时崩溃
【发布时间】:2016-11-09 22:42:04
【问题描述】:

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

说明

汽车 (.car_ownerships) (.car) CarOwnership (.person) (.car_ownerships)

汽车 (.people) (.cars)

问题

删除汽车时 SA 首先删除关联对象 CarOwnership(因为与 secondary 参数的“直通”关系),然后尝试将相同关联对象中的外键更新为 NULL,从而导致崩溃。 p>

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

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

编辑:实际上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()
# ...

诊断

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

#### 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

我们可以使用关联代理来尝试实现“通过”关系。

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

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)

【问题讨论】:

    标签: python sqlalchemy many-to-many


    【解决方案1】:

    您使用的是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”关系与关联表称为“car_ownerships”这一事实无关,因此我以不同的方式命名它们。

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

    【讨论】:

    • 但这不是我想做的。在这里,您刚刚将car_ownerships 关系(在backref 中定义)重命名为carspeople,并删除了直通关系。您提案中的carspeople 并不是真正的CarPerson 对象,只是CarOwnership。有没有办法与 SA 中的关联对象建立直通关系?我必须为此使用关联代理吗?
    • 正确。我添加了一个使用association_proxy的示例。
    • 谢谢!但是您的示例不起作用(您是否对其进行了测试?)因为它似乎缺少构造函数。查看我的编辑。
    • 我修改了第二个代码块来执行此操作,而没有在 CarOwnership 上创建自定义构造函数。
    • 它确实有效。用我发布的第二个代码块替换您问题中的 3 个类。您可以单击我的答案下方的“已编辑 x 分钟前”以查看差异。
    【解决方案2】:

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

    在这里,我们编辑从依赖对象 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多