Home > Software engineering >  return response number of count in django rest framework
return response number of count in django rest framework

Time:09-02

  • I wanted to return the response number of the count of chiled_comments as in blew table.
  • like for id no. 3 have 2(count) "parent_post_comment_id".
  • and same as id no. 1 have only 1(count) "parent_post_comment_id".
id is_post_comment parent_post_comment_id created_on description language_post_id
1 1 2022-08-30 09:06:07.078366 Comment Create 001!!! 2
2 1 2022-08-30 09:11:23.255055 Comment Create 002!!! 2
3 1 2022-08-30 09:16:45.394074 Comment Create 003!!! 2
4 0 3 (child of comment 3) 2022-08-30 12:26:48.076494 Comment Create 003-1!!! 2
5 0 3 (child of comment 3) 2022-08-30 12:27:10.384464 Comment Create 003-2!!! 2
6 0 2 (child of comment 2) 2022-08-30 12:27:27.306202 Comment Create 002-1!!! 2
7 0 2 (child of comment 2) 2022-08-30 12:27:37.405487 Comment Create 002-2!!! 2
8 0 1 (child of comment 1) 2022-08-30 12:27:53.771812 Comment Create 001-1!!! 2

models.py

class Comments(models.Model):
    language_post = models.ForeignKey(PostInLanguages, null=False, related_name='comment_data', on_delete=models.CASCADE)
    is_post_comment = models.BooleanField(default=True)
    parent_post_comment_id = models.PositiveIntegerField(null=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    description = models.CharField(max_length=400, blank=False)
    created_on = models.DateTimeField(default=timezone.now)

views.py

class CommentGetView(viewsets.ViewSet):

    def retrieve(self, request, post_id=None, post_language_id=None, *args, **kwargs):

        try:
            post_in_lang = PostInLanguages.objects.get(id=post_language_id)

            post_in_lang_id = post_in_lang.id
        except PostInLanguages.DoesNotExist as e:
            return Response({"response": False, "return_code": "languages_post_not_exist", "result": "Comment_Get_Failed", "message": errors["postinlanguages_DoesNotExist"]},  status=status.HTTP_400_BAD_REQUEST)

        try:
            queryset = Comments.objects.filter(language_post_id=post_in_lang_id,is_post_comment=True)

        except Comments.DoesNotExist as e:
            return Response({"response": False, "return_code": "comments_not_exist", "result": "Comment_Get_Failed", "message": errors["comments_DoesNotExist"]},  status=status.HTTP_400_BAD_REQUEST)

        try:
            if post_in_lang.post_id != post_id:
                return Response({"response": False, "return_code": "post_not_match", "result": "Comment_Get_Failed", "message": errors["post_not_match"]},  status=status.HTTP_400_BAD_REQUEST)

            else:
                paginator = CustomPageNumberPagination()
                response = paginator.generate_response(queryset, CommentResponseSerializer, request)

        except Exception as error:
            return Response({"response": False, "return_code": "internal_code_error", "result": "Comment_Get_Failed", "message": str(error)},  status=status.HTTP_400_BAD_REQUEST)
        return response

serilizer.py

class CommentResponseSerializer(serializers.ModelSerializer):

    chiled_comments= serializers.IntegerField(source='comment_data.count', read_only=True)
    likes_count = serializers.IntegerField(source='comment_like_model.count', read_only=True)

    class Meta:
        model = Comments
        fields = ('id', 'user_id', 'language_post_id', 'is_post_comment', \
'parent_post_comment_id', 'description', 'created_on', 'likes_count', 'chiled_comments')

output should

{
    "response": true,
    "return_code": "success",
    "result": [
        {
            "id": 1,
            "user_id": 2,
            "language_post_id": 2,
            "is_post_comment": true,
            "parent_post_comment_id": null,
            "description": "Comment Create 005!!!",
            "created_on": "2022-08-30T09:06:07",
            "chiled_comments": 1,
            "likes_count": 0
        },
        {
            "id": 2,
            "user_id": 2,
            "language_post_id": 2,
            "is_post_comment": true,
            "parent_post_comment_id": null,
            "description": "Comment Create 005!!!",
            "created_on": "2022-08-30T09:11:23",
            "chiled_comments": 2,
            "likes_count": 0
        },
        {
            "id": 3,
            "user_id": 2,
            "language_post_id": 2,
            "is_post_comment": true,
            "parent_post_comment_id": null,
            "description": "Comment Create 005!!!",
            "created_on": "2022-08-30T09:16:45",
            "chiled_comments": 2,
            "likes_count": 0
        },
        
    ],
    "message": "Success",
    "next": null,
    "previous": null,
    "total_count": 3
}

Getting Output

{
    "response": true,
    "return_code": "success",
    "result": [
        {
            "id": 1,
            "user_id": 2,
            "language_post_id": 2,
            "is_post_comment": true,
            "parent_post_comment_id": null,
            "description": "Comment Create 005!!!",
            "created_on": "2022-08-30T09:06:07",
            "likes_count": 0
        },
        {
            "id": 2,
            "user_id": 2,
            "language_post_id": 2,
            "is_post_comment": true,
            "parent_post_comment_id": null,
            "description": "Comment Create 005!!!",
            "created_on": "2022-08-30T09:11:23",
            "likes_count": 0
        },
        {
            "id": 3,
            "user_id": 2,
            "language_id": 2,
            "language_post_id": 2,
            "is_post_comment": true,
            "parent_post_comment_id": null,
            "description": "Comment Create 005!!!",
            "created_on": "2022-08-30T09:16:45",
            "likes_count": 0
        }
    ],
    "message": "Success",
    "next": null,
    "previous": null,
    "total_count": 3
}

CodePudding user response:

With your current setup, the minimal thing you can do is:

class CommentResponseSerializer(serializers.ModelSerializer):
    child_comments = serializers.SerializerMethodField()
    
    def get_child_comments(self, comment: Comment):
        return Comment.objects.filter(parent_post_comment_id=comment.id).count()

comment_data only works if you're dealing with PostInLanguages objects

  • Related