SQLAlchemy DELETE Error caused by having a both lazy-load AND a dynamic version of the same relationship

前端 未结 2 649
礼貌的吻别
礼貌的吻别 2020-12-16 00:59

Here is some example code:

users_groups = Table(\'users_groups\', Model.metadata,
    Column(\'user_id\', Integer, ForeignKey(\'users.id\')),
    Column(\'gr         


        
相关标签:
2条回答
  • 2020-12-16 01:17

    I just add another simple workaround.

    You can delete the collections before deleting the item itself:

    >>> for user in group.users:
            group.users.remove(user)
    >>> db.session.delete(group)
    >>> db.session.commit()
    

    Alternatively, you can also set it as an empty list:

    >>> group.users = []
    >>> db.session.commit()
    >>> db.session.delete(group)
    >>> db.session.commit()
    
    0 讨论(0)
  • 2020-12-16 01:28

    both the Group.users and Group.users_dynamic relationships are attempting to reconcile the fact that the Group is being deleted along with being able to manage the User() objects they refer to; one relationship succeeds while the second one fails, as the rows in the association table were already deleted. The most straightforward solution is to mark all but one of the identical relationships as viewonly:

    class Group(Base):
        __tablename__ = 'groups'
        id = Column(Integer, primary_key=True)
    
        users = relationship('User', secondary=users_groups, lazy='select', backref='groups')
        users_dynamic = relationship('User', viewonly=True, secondary=users_groups, lazy='dynamic')
    

    if you're still wanting to have both relationships handle some degree of mutations, you'd need to do this carefully as SQLAlchemy doesn't know how to coordinate among changes in two relationships at the same time, so conflicts like this can continue to happen (like double inserts, etc) if you make equivalent mutations on both relationships. To just take care of the "delete" issue by itself, you can also try setting Group.users_dynamic to passive_deletes=True:

    class Group(Base):
        __tablename__ = 'groups'
        id = Column(Integer, primary_key=True)
    
        users = relationship('User', secondary=users_groups, lazy='select', backref='groups')
        users_dynamic = relationship('User', passive_deletes=True, secondary=users_groups, lazy='dynamic')
    
    0 讨论(0)
提交回复
热议问题