簡體   English   中英

將pymysql注釋對象遞歸轉換為樹

[英]Converting pymysql Comment objects to tree recursively

我正在嘗試創建一個注釋系統,作為一個業余項目的一部分,但是當從數據庫中獲取注釋對象時,我無法弄清楚如何對注釋對象進行遞歸排序。 我正在使用具有以下數據模型的關系數據庫:

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 %}

我沒有弄清楚在執行此操作之前如何對數據進行排序。

非常簡單的方法是這樣的:

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

這里的解決方案與您向我們展示的預期輸出匹配。


但是,如果您想有一棵真正的樹,請嘗試此操作

def comments_to_dict(comments):
    index = {}
    for comment in comments:
        index[comment.id] = {
            'comment': comment,
            'children': []
        }
    for obj in index.itervalues():
        pid = obj['comment'].parent_id
        index[pid]['children'].append(obj)
    return index

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM