[Answered ]-How to hide certain json data from passing through if it doesn't meet a condition in Django rest framework?

1👍

Your CommentSerializer is correct problem is you are getting all comments and related replies from Comment model in your view and passing to CommentSerializer you need to filter and remove reply related to comment

Comment.objects.filter(reply_id__isnull=True)

0👍

set reply_id field as write_only

class CommentSerializer(serializers.ModelSerializer):
    content = serializers.CharField()
    reply_id = serializers.PrimaryKeyRelatedField(
        source='reply',
        queryset=Comment.objects.all(),
        required=False,
        write_only=True
    )
    user = serializers.ReadOnlyField(source="user.username")
    replies = CommentCreateSerializer(many=True, read_only=True)

    class Meta:
        model = Comment
        fields = ['id', 'user', 'content', 'replies', 'reply_id', 'timestamp']
👤JPG

0👍

Serializers validation will work fine in this case.
If you need to add a condition to a specific field then create a method validate_fieldname and if you want to add condition over a specific object then directly create a method as validate.

You can read the documentation for more information – https://www.django-rest-framework.org/api-guide/serializers/#field-level-validation

0👍

In your case you need to filter as @Chandan said before. So really you need to refactor your view with the reply_id filter

    permission_classes = (IsAuthenticated,) 
    # pagination_class = PageNumberPagination

    def get(self, *args, **kwargs):
        post                = get_object_or_404(Post, slug=self.kwargs['slug'])
        comments            = Comment.objects.filter(post=post,reply_id__isnull=True)
        paginator           = CustomPaginator()
        response            = paginator.generate_response(comments, CommentSerializer, self.request)
        return response
👤edilio

Leave a comment