具有关联对象的多对多和所有关系在删除

时间:2016-07-07 14:41:08

标签: python sqlalchemy many-to-many

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

描述

汽车.car_ownerships)< - > (.car CarOwnership .person)< - > (.car_ownerships

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

问题

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

我该如何解决这个问题?我有点困惑,因为我认为这种模式很常见: - /。我错过了什么?

我知道我可以通过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()

正在删除 - &gt;崩溃

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()有一个创建者参数,可以减少我最终在下面使用的怪异构造函数的需要。

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)

2 个答案:

答案 0 :(得分:2)

您正在使用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时出错。您的汽车和个人的关联代理不能同时使用“汽车所有权”和“汽车所有权”。关系,这就是为什么我有一个名为&#39; people_association&#39;和一个名为&#39; cars_association&#39;。

&#39; car_ownerships&#39;你所拥有的关系与关联表被称为“car_ownerships”这一事实无关,因此我将它们命名为不同。

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

答案 1 :(得分:2)

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

在这里,我们编辑从依赖对象 Car Person 到关联对象 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)
相关问题