【问题标题】:Query Tree Model in DjangoDjango中的查询树模型
【发布时间】:2015-06-23 08:28:46
【问题描述】:

您通常如何查询可以嵌套的评论线程?

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 的孩子,但它只返回直接孩子。我必须在我的序列化程序中编写自定义查询吗?

【问题讨论】:

    标签: python django serialization model django-rest-framework


    【解决方案1】:

    您是否考虑使用Django-treebeard?它在内部完成存储树的正确索引的工作,以便高效地查询它。我强烈推荐它。

    【讨论】:

      猜你喜欢
      • 2017-08-10
      • 2015-07-13
      • 1970-01-01
      • 2019-03-22
      • 1970-01-01
      • 2012-12-15
      • 2018-09-13
      • 2010-09-26
      相关资源
      最近更新 更多