简体   繁体   English

Flask SQLAlchemy 自引用排序列表

[英]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.我只想要一个由有序节点组成的树,排序由 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 .我不得不将 children 和 parent 属性分开,并使用back_populates而不是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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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