简体   繁体   中英

Flask SQLAlchemy self-referential ordering list

I am trying to make a self-referential tree with ordered children, but I can't seem to get it right. This is what gets me the closest, but the behavior is very unexpected.

I am wondering what I am doing wrong, and I have not been able to find a self-referential example using an ordering list.

I just want a tree made out of ordered nodes with the ordering being handled by sql-alchemy. Thank you!

class Node(db.Model):
  id = db.Column(db.Integer, primary_key = True)
  parent_id = db.Column(db.Integer, db.ForeignKey('node.id'))
  index = db.Column(db.Integer)
  children = db.relationship('Node', order_by = 'Node.index', collection_class = ordering_list('index'), backref='parent', remote_side = [id], uselist = True)

I had to separate out the children and parent attributes and use back_populates instead of backref .

Solution:

class Node(db.Model):
  id = db.Column(db.Integer, primary_key = True)
  parent_id = db.Column(db.Integer, db.ForeignKey('node.id'))
  index = db.Column(db.Integer)
  parent = db.relationship('Node', remote_side = 'Node.id', back_populates = 'children')
  children = db.relationship('Node', order_by = 'Node.index', collection_class = ordering_list('index'), back_populates = 'parent')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM