简体   繁体   English

Django中的查询树模型

[英]Query Tree Model in Django

How do you usually query comment thread that can be nested? 您通常如何查询可嵌套的注释线程?

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]
"""

In the example above, I created a tree 在上面的示例中,我创建了一棵树

            c1
     c11          c12
c111   c112

and tried to query the child of c1, but it only returns the immediate child. 并尝试查询c1的子代,但它仅返回直接子代。 Do I have to write custom query in my serializer? 我必须在序列化器中编写自定义查询吗?

Have you consider using Django-treebeard ? 您是否考虑过使用Django-treebeard It internally does the job of storing the correct indexes of your tree in such a way that it is efficient to query it. 它在内部以有效查询树的方式来存储树的正确索引。 I highly recommend it. 我强烈推荐它。

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

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