Search code examples
pythonflasksqlalchemyflask-sqlalchemyflask-admin

Self referential relationship is disappearing in flask-admin


Hope you can help me!

I have a relationship in sqlalchemy as follows:

class Location(db.Model, DateModified, Sluggable):
    __tablename__ = 'location'
    __sluggable__ = {
        'populate_from': 'title',
        'always_update': True
    }    
    id = db.Column(db.Integer, primary_key=True)

    title = db.Column(db.String(80))

    ...

    parent_location_id = db.Column(db.Integer, db.ForeignKey('location.id'), index=True)
    parent_location = db.relationship(lambda: Location, remote_side=id, backref='child_locations')

I'm really uncertain as to how to debug the fact that intermittently flask-admin or sqlalchemy is loosing the parent_location_id when the parent location is saved.

This disappearing act seems to be fairly random.

Anyone with any clue as to how I debug this would help immensely!

Thanks.


Solution

  • Joes, thanks for reminding me to answer this.

    It was simply that I had a backref in my models that was hidden on the form. Therefore, the data being submitted was empty clearing the relationships.

    Moral of the story: Don't have back refs that are hidden in your admin forms.