Hi,
so i am making reddit style tree comment system for django-ninja
.
The way i achieved this is with this code :
# models.py from apps.user.models import CustomUser from django.db import models from treenode.models import TreeNodeModel # Create your models here. class EpisodeCommentModel(TreeNodeModel): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) text = models.TextField() comment_added = models.DateTimeField(auto_now=True) def __str__(self) -> str: return f"{self.user} | {self.text}" class Meta(TreeNodeModel.Meta): verbose_name = "Episode Comment" verbose_name_plural = "Episode Comments"
# views.py @router.get( "/{int:anime_id}/episodes/{str:episode_number}/comments", response=list[EpisodeCommentTreeSchema], ) def get_individual_anime_episode_comments( request: HttpRequest, anime_id: int, episode_number: str, ): query: list[EpisodeCommentModel] = get_list_or_404( get_object_or_404( AnimeModel, pk=anime_id, ) .episodes.get(episode_number__in=[episode_number]) .episode_comments.all() ) return_list = [] def get_nested_children(item: EpisodeCommentModel): __list__ = [] __list__.append( { "user": str(item.user), "text": item.text, "comment_added": item.comment_added, "children": [get_nested_children(i)[0] for i in item.get_children()], } ) return __list__ for i in query: return_list.append(get_nested_children(i)[0]) return return_list
# schema.py class EpisodeCommentTreeSchema(Schema): user: str text: str comment_added: datetime.datetime children: list["EpisodeCommentTreeSchema"] = []
Which returns
[ { "user": "baseplate-admin#0001", "text": "1", "comment_added": "2023-04-04T15:37:17.350Z", "children": [ { "user": "baseplate-admin#0001", "text": "2", "comment_added": "2023-04-03T16:17:53.050Z", "children": [ { "user": "baseplate-admin#0001", "text": "3", "comment_added": "2023-04-03T16:18:13.588Z", "children": [] } ] }, { "user": "baseplate-admin#0001", "text": "2", "comment_added": "2023-04-04T15:51:39.823Z", "children": [] } ] }, { "user": "baseplate-admin#0001", "text": "2", "comment_added": "2023-04-03T16:24:58.779Z", "children": [] } ]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4