2017-01-05 1 views
0

취미 프로젝트의 일부로 코멘트 시스템을 만들려고하지만 데이터베이스에서 가져온 Comment 객체를 재귀 적으로 정렬하는 방법을 알지 못합니다. 내가 나무에서 이러한 개체를 정렬 할 필요가 데이터베이스에서 데이터를했으면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 및 기타 유사한 소셜 미디어 사이트에 사용 된 댓글 시스템과 거의 같습니다. 내가 플라스크 신사를 사용하고 있는데 아마도 나는이 문서에서 찾을 같은 것을 할 수있는 렌더링 : 나는이 일을하기 전에 데이터를 정렬하는 방법

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

내가 아니에요 것입니다 파악. 그래서 먼저 children 비어 후 두 번째 패스에서 당신이 기입 아이들과 루트 요소를 채울

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 

:

답변

1

매우 간단한 방법이있다. 이것은 더 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 
+0

을 시도하지만이 댓글의 무한히 깊은 나무를 허용한다면? – Marius

+1

@ 마리우스 임의의 깊은 나무는 두 번 통과 할 수 있습니다. 답변을 업데이트했습니다. 이전과 마찬가지로 단일 단계로 구현할 수 있습니다. 운동으로 당신에게 맡기겠습니다. – freakish