[英]Query Tree Model in Django
您通常如何查询可嵌套的注释线程?
from django.db import models
class Comment (models.Model):
# if parent is blank, comment is top level
parent = models.ForeignKey('Comment',
related_name='children',
null=True)
text = models.TextField(blank=True)
def __repr__(self):
return self.text
"""
from tree.models import Comment
c1 = Comment(text='c1')
c1.save()
c11 = Comment(text='c11', parent=c1)
c12 = Comment(text='c12', parent=c1)
c11.save()
c12.save()
c111 = Comment(text='c111', parent=c11)
c112 = Comment(text='c112', parent=c11)
c111.save()
c112.save()
c1.children.all() -> return [c111, c112] should return [c111, c112, c11, c12]
"""
在上面的示例中,我创建了一棵树
c1
c11 c12
c111 c112
并尝试查询c1的子代,但它仅返回直接子代。 我必须在序列化器中编写自定义查询吗?
您是否考虑过使用Django-treebeard ? 它在内部以有效查询树的方式来存储树的正确索引。 我强烈推荐它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.