Note that there are some explanatory texts on larger screens.

plurals
  1. POSetting delete-orphan on SQLAlchemy relationship causes AssertionError: This AttributeImpl is not configured to track parents
    primarykey
    data
    text
    <p>this is my Flask-SQLAlchemy Declarative code:</p> <pre><code>from sqlalchemy.ext.associationproxy import association_proxy from my_flask_project import db tagging = db.Table('tagging', db.Column('tag_id', db.Integer, db.ForeignKey('tag.id', ondelete='cascade'), primary_key=True), db.Column('role_id', db.Integer, db.ForeignKey('role.id', ondelete='cascade'), primary_key=True) ) class Tag(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), unique=True, nullable=False) def __init__(self, name=None): self.name = name @classmethod def delete_orphans(cls): for tag in Tag.query.outerjoin(tagging).filter(tagging.c.role_id == None): db.session.delete(tag) class Role(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='cascade')) user = db.relationship('User', backref=db.backref('roles', cascade='all', lazy='dynamic')) ... tags = db.relationship('Tag', secondary=tagging, cascade='all', backref=db.backref('roles', cascade='all')) tag_names = association_proxy('tags', 'name') __table_args__ = ( db.UniqueConstraint('user_id', 'check_id'), ) </code></pre> <p>Basically, it's many-to-many tagging with Declarative. When deleting some entries from tagging, I want SQLAlchemy to tidy up the orphans. As I found out in docs, to turn on this feature, I should do this:</p> <pre><code>class Role(db.Model): ... tags = db.relationship('Tag', secondary=tagging, cascade='all,delete-orphan', backref=db.backref('roles', cascade='all')) ... </code></pre> <p>However, such setting leads to <strong>AssertionError: This AttributeImpl is not configured to track parents.</strong> I googled it and found nothing except of the opensourced code of SQLAlchemy. Therefore, I created the classmethod <code>Tag.delete_orphans()</code> (it's in the code above) to call it every time I think some orphans could occure, but that doesn't seem to be very elegant.</p> <p>Any ideas or explanations why my setting with <code>delete-orphan</code> doesn't work?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload