Home > OS >  Filter nested serializer model field (exclude particular field)
Filter nested serializer model field (exclude particular field)

Time:02-01

I am new to Django and I am trying to exclude a model field in nested serializer.

modals.py

class Blog(models.Model):
    title = models.CharField(max_length=30)
    description = models.CharField(max_length=30)

class Comment(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name="comment")
    comment_bdy = models.CharField(max_length=30)
    completed = models.BooleanField(default=False)

serializers.py

class BlogCommentSerializer(serializers.ModelSerializer):

    class Meta:
        model = Comment
        fields = ("id", "comment_body")

class BlogSerializer(serializers.ModelSerializer):
    comment = BlogCommentSerializer(many=True)
    
    class Meta:
        model = ("id", "title", "description", "comment",)

I am trying to exclude comment which have completed=True .

I have tried many times like :-

class BlogCommentSerializer(serializers.ModelSerializer):

    def to_representation(self, data):
        data = data.filter(completed=False)
        return super(BlogCommentSerializer, self).to_representation(data)

But It showing:

AttributeError: 'CommentReply' object has no attribute 'filter'

Then I tried using:

class BlogSerializer(serializers.ModelSerializer):

    def get_comment(self, instance):
        comment_instance = instance.comment_set.exclude(completed=True)
        return BlogSerializer(comment_instance , many=True).data

It also didn't work.

What I am trying to do

I am trying to exclude comments which are completed=True.

CodePudding user response:

You can try like this using SerializerMethodField:

class BlogSerializer(serializers.ModelSerializer):
    comment = serializers.SerializerMethodField()

    def get_comment(self, instance):
        comment_instances = instance.comment.exclude(completed=True)
        return BlogCommentSerializer(comment_instances , many=True).data

CodePudding user response:

Try it:

class BlogSerializer(serializers.ModelSerializer):
    comment = serializers.SerializerMethodField()

    def get_comment(self, obj):
        queryset = Comment.objects.
            filter(blog=obj).exclude(blog__completed=True)
        return [BlogCommentSerializer(q).data for q in queryset]
  • Related