###やりたいこと
再帰処理でコメントを階層的に表示させているが、親(一番上のコメント)にいくつコメントがついているか、子供や孫すべて含めてカウントして表示させたい。
再帰処理にはMPTTを使用しています。
###現状
Python
1# -------------------------- 2# models.py 3# -------------------------- 4class Post(MPTTModel): 5 parent = TreeForeignKey( 6 'self', null=True, blank=True, related_name='children', 7 db_index=True, on_delete=models.DO_NOTHING) 8 9# -------------------------- 10# views.py 11# -------------------------- 12class PostListView(ListView): 13 model = Post 14 context_object_name = 'posts' 15 template_name = 'boards/thread_posts.html' 16 17 def get_context_data(self, **kwargs): 18 self.thread.views += 1 19 self.thread.save() 20 kwargs['thread'] = self.thread 21 return super().get_context_data(**kwargs) 22 23 def get_queryset(self): 24 thread_model = Thread.objects.annotate( 25 tag_num=Count('tag')).order_by('-tag_num') 26 27 self.thread = get_object_or_404( 28 thread_model, 29 category__pk=self.kwargs.get('pk'), 30 pk=self.kwargs.get('thread_pk')) 31 queryset = self.thread.posts.order_by('page') 32 return queryset 33 34# -------------------------- 35# post_list.html 36# -------------------------- 37# 一番上にどのページにいくつコメントがついているか表示させたい。 38# しかしこのコードでは、一番上の親直下(子供)の数しか取得できていない 39{% for post in posts %} 40 <!-- 一番最初のpostのみ表示 --> 41 {% if not post.parent %} 42 <p>{{ post.page}} |{{ post.children.count }}</p> 43 {% endif %} 44{% endfor %} 45 46: 47 48# postの内容を表示 49{% recursetree posts %} 50 <div> 51 <li> 52 <!-- 一番最初の投稿のみページ数を表示 --> 53 {% if not node.parent %} 54 <div class="card-header border-info py-2 px-3"> 55 ページ: {{ node.page }} 56 </div> 57 {% endif %} 58 59 : 60 61 <ul> 62 {% if not node.is_leaf_node %} 63 {{ children }} 64 {% endif %} 65 </ul> 66 </li> 67 </div> 68{% endrecursetree %}
あなたの回答
tips
プレビュー