我有以下自引用(树)节点,并希望通过计算的属性uuid_path
和过滤/排序name_path
:
class Node (db.Model):
id = db.Column (db.Integer, db.Sequence ('node_id_seq'), primary_key=True)
###########################################################################
root_id = db.Column (db.Integer, db.ForeignKey (id, ondelete='CASCADE'),
index=True)
nodes = db.relationship ('Node',
cascade='all, delete-orphan', lazy='dynamic',
primaryjoin='Node.id==Node.root_id',
backref=db.backref ('root', remote_side=id))
###########################################################################
_uuid = db.Column (db.String (36), nullable=False, index=True, unique=True,
name = 'uuid')
_name = db.Column (db.Unicode (256), nullable=False, index=True,
name = 'name')
###########################################################################
@hybrid_property
def uuid (self):
return self._uuid
@hybrid_property
def name (self):
return self._name
@name.setter
def name (self, value):
self._name = value
###########################################################################
def __init__ (self, name, root, mime=None, uuid=None):
self.root = root
self._uuid = uuid if uuid else str (uuid_random ())
self._name = unicode (name) if name is not None else None
def __repr__ (self):
return u'<Node@%x: %s>' % (self.id if self.id else 0, self._name)
###########################################################################
@hybrid_property
def uuid_path (self):
node, path = self, []
while node:
path.insert (0, node.uuid)
node = node.root
return os.path.sep.join (path)
@hybrid_property
def name_path (self):
node, path = self, []
while node:
path.insert (0, node.name)
node = node.root
return os.path.sep.join (path)
###########################################################################
如果我得到一个Node
实例subnode
并执行 egsubnode.name_path
然后我得到正确的 eg root/subnode
。但是,如果我尝试使用Node.name_path
(用于过滤/排序),那么 SQLAlchemy 会抱怨:
Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Node.root has an attribute 'name'.
我很确定我必须介绍以下内容:
class Node (db.Model):
@hybrid_property
def name_path (self):
node, path = self, []
while node:
path.insert (0, node.name)
node = node.root
return os.path.sep.join (path)
@name_path.expression
def name_path (cls):
## Recursive SQL expression??
但是我很难为@name_path.expression
(或@uuid_path.expression
)得到正确的定义;它应该以某种方式指示 SQL 将路径从根节点传递到相关节点。
我不明白为什么这是必需的,因为我告诉 SQLAlchemy 迭代计算路径值。谢谢你的帮助。