Flask 如何在自引用表中返回子级的父级?

Flask 如何在自引用表中返回子级的父级?,flask,sqlalchemy,flask-sqlalchemy,Flask,Sqlalchemy,Flask Sqlalchemy,我建立这个模型是为了管理我网站的内容。这似乎很管用,只是我不知道如何显示一个特定“孩子”的“父母” 数据结构 这允许我将内容组织到树中 Parent --- child 1 --- child 2 --- child 3 --------grandchild 1 --------grandchild 2 模型 这是有效的 >>> Service.query.filter_by(slug="/about").all() [About] 这也是 >>> Ser

我建立这个模型是为了管理我网站的内容。这似乎很管用,只是我不知道如何显示一个特定“孩子”的“父母”

数据结构 这允许我将内容组织到树中

Parent
--- child 1
--- child 2
--- child 3
--------grandchild 1
--------grandchild 2
模型 这是有效的

>>> Service.query.filter_by(slug="/about").all()
[About]
这也是

>>> Service.query.filter_by(parent=None).all()
[]
这不管用

>>> Service.query.filter_by(parent="/about").all()

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/jwogrady/.virtualenvs/medcol/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 1296, in filter_by
    for key, value in kwargs.items()]
  File "/Users/jwogrady/.virtualenvs/medcol/lib/python2.7/site-packages/sqlalchemy/sql/operators.py", line 298, in __eq__
    return self.operate(eq, other)
  File "/Users/jwogrady/.virtualenvs/medcol/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py", line 176, in operate
    return op(self.comparator, *other, **kwargs)
  File "/Users/jwogrady/.virtualenvs/medcol/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py", line 1002, in __eq__
    other, adapt_source=self.adapter))
  File "/Users/jwogrady/.virtualenvs/medcol/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py", line 1338, in _optimized_compare
    value = attributes.instance_state(value)
AttributeError: 'str' object has no attribute '_sa_instance_state'
>>Service.query.filter_by(parent=“/about”).all()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“/Users/jwogrady/.virtualenvs/medcol/lib/python2.7/site packages/sqlalchemy/orm/query.py”,第1296行,在filter_by中
对于键,以kwargs.items()为单位的值
文件“/Users/jwogrady/.virtualenvs/medcol/lib/python2.7/site packages/sqlalchemy/sql/operators.py”,第298行,在__
返回自操作(eq,其他)
文件“/Users/jwogrady/.virtualenvs/medcol/lib/python2.7/site packages/sqlalchemy/orm/attributes.py”,第176行,在operate中
返回op(自比较器,*其他,**kwargs)
文件“/Users/jwogrady/.virtualenvs/medcol/lib/python2.7/site packages/sqlalchemy/orm/relationships.py”,第1002行,在__
其他,adapt_source=self.adapter)
文件“/Users/jwogrady/.virtualenvs/medcol/lib/python2.7/site packages/sqlalchemy/orm/relationships.py”,第1338行,在“优化”比较中
值=属性。实例\状态(值)
AttributeError:“str”对象没有属性“\u sa\u instance\u state”

对于给定的子项,如何获取父项?

若要获取具有带“about”slug的父项的所有服务,请使用以下比较:

Service.query.filter(Service.parent.has(Service.slug == '/about')).all()
或者,为了在非常大的表上获得更好的性能,请使用别名和联接:

parent = db.aliased(Service)
Service.query.join((parent, parent.id == Service.parent_id)).filter(parent.slug == '/about').all()

如果您的字面意思是“如何获取给定服务的父服务”,则只需使用
s.parent
从实例访问它

parent = db.aliased(Service)
Service.query.join((parent, parent.id == Service.parent_id)).filter(parent.slug == '/about').all()