将pymysql Comment对象递归转换为树

时间:2017-01-05 13:36:24

标签: python algorithm sqlite recursion pymysql

我正在尝试创建一个评论系统作为业余爱好项目的一部分,但我无法弄清楚如何从数据库中提取它们后递归排序。我正在使用具有以下数据模型的关系数据库:

class Comment(Base):
    __tablename__ = 'comments'
    id = Column(Integer, primary_key=True)
    comment = Column(String(), nullable=False)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
    post_id = Column(Integer, ForeignKey('posts.id'), nullable=False)
    parent_id = Column(Integer, ForeignKey('comments.id'), nullable=False)

一旦我从数据库获得数据,我需要在树中对这些对象进行排序。示例输入可以是例如:

comments = [
            <models.Comment object at 0x104d80358>,
            <models.Comment object at 0x104d803c8>,
            <models.Comment object at 0x104d80470>, 
            <models.Comment object at 0x104d80518>,
            <models.Comment object at 0x104d805c0>,
            <models.Comment object at 0x104d80668>
           ]

预期结果可能是:

comment_dict = {1: {'comment':<Comment.object>, 'children':[]},
               {2: {'comment':<Comment.object>, 'children':[<Comment.object>, ...]},
               {3: {'comment':<Comment.object>, 'children':[]},
               {4: {'comment':<Comment.object>, 'children':[<Comment.object>, ...]} ...

任何评论对象都可以拥有无​​限量的孩子。几乎像reddit和其他类似社交媒体网站上使用的评论系统。 对于渲染,我正在使用flask和Jinja,并且可能会执行类似我在文档中找到的内容:

<ul class="sitemap">
{%- for item in sitemap recursive %}
    <li><a href="{{ item.href|e }}">{{ item.title }}</a>
    {%- if item.children -%}
        <ul class="submenu">{{ loop(item.children) }}</ul>
    {%- endif %}</li>
{%- endfor %}

在执行此操作之前,我如何对数据进行排序是我无法解决的问题。

1 个答案:

答案 0 :(得分:1)

非常简单的方法是:

subview.hidden = true

首先,您将def comments_to_dict(comments): result = {} for comment in comments: result[comment.id] = { 'comment': comment, 'children': [] } for comment in comments: result[comment.parent_id]['children'].append(comment) return result 的根元素填充为空,然后在第二遍中填充子项。只需对children进行一次传递即可进一步改善这一点:

comments

此处的解决方案与您向我们展示的预期输出相匹配。

如果您想要一棵真正的树,那么试试这个

def comments_to_dict(comments):
    result = {}
    for comment in comments:
        if comment.id in result:
            result[comment.id]['comment'] = comment
        else:
            result[comment.id] = {
                'comment': comment,
                'children': []
            }

        if comment.parent_id in result:
            result[comment.parent_id]['children'].append(comment)
        else:
            result[comment.parent_id] = {
                'children': [comment]
            }
    return result