Get separate serializer response for each nested serializer

Stuck with serializer where I need to have serialized response based on the nested serializer.

Models.py :

class Parent(models.Model):
    name = models.CharField(max_length=50)

class Child(models.Model):
    parent = models.ForeignKey(Parent, related_name='children')
    child_name = models.CharField(max_length=80)

Serialziers.py

class ChildSerializer(serializers.ModelSerializer):
    class Meta:
        model = Child
        fields = '__all__'

class ParentSerializer(serializers.ModelSerializer):
    child = serializers.SerializerMethodField()
    
    def get_child(self, obj):
        childs = Child.objects.filter(parent=obj)
        return ChildSerializer(childs, many=True).data

    class Meta:
        model = Parent
        fields = '__all__'

I am getting output like below where I am getting nested childs:

{
    id : 1,
    name : "Parent1",
    child: [
        0: {id : 1, child_name : "child1"}
        1: {id : 2, child_name : "child2"}
    ]
}

But for some business purpose I need output to be something like below, where serializer should be based on child. i.e. for each child there should be separate Parent serializer. Doesn't matter if it has same id and other fields. :

{
    0:{
        id : 1,
        name : "Parent1",
        child: [
            0: {id : 1, child_name : "child1"}
        ]
    }
    1:{
        id : 1,
        name : "Parent1",
        child: [
            0: {id : 2, child_name : "child2"}
        ]
    }
}

Also please let me know if I can filter based on the child serializer. i.e. childs I will be passing to Parent serializer and get response for each childs.



Read more here: https://stackoverflow.com/questions/68455569/get-separate-serializer-response-for-each-nested-serializer

Content Attribution

This content was originally published by Shivendra Pratap Kushwaha at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: