0

How Parent object will create in Django Restframework nested serializers? I want to show all children associated to the parent but the problem is that when I try to create Parent it asks children list and as per the rule first parent will born

models

class Parent(models.Model)                                          
    name = models.CharField(max_length=30)
class Child(models.Model)
    parent = models.ForeignKey(Parent, on_delete=models.CASCADE)
    name = models.CharField(max_length=30)

Serializers

class ChildSerializer(ModelSerializer):
    class Meta:
        model = Child
        fields = ('name')
class ParentSerializer(ModelSerializer):
    children = ChildSerializer(many=True)
    class Meta:
        model = Parent
        fields = ('name','children')

views.py

class ParentViewSet(ModelViewSet):
    serializer_class = ParentSerializer
    queryset = Parent.objects.all()

Response:

{
    "children": [
        "This field is required."
    ]
}
5
  • can you add the code you are using to create parent Commented Dec 16, 2018 at 13:40
  • it is simple ModelViewSet Commented Dec 16, 2018 at 13:41
  • I'm getting this response :{ "children": [ "This field is required." ] } Commented Dec 16, 2018 at 13:42
  • it would be more helpful if you add code Commented Dec 16, 2018 at 13:45
  • @nishant I've made the changes in question Commented Dec 16, 2018 at 13:50

2 Answers 2

1

update your parentserializer with this

class ParentSerializer(ModelSerializer):
children = ChildSerializer(many=True, read_only=True)
class Meta:
    model = Parent
    fields = ('name','children')

update childSerializer with

class ChildSerializer(ModelSerializer):
class Meta:
    model = Child
    fields = ('name',)
Sign up to request clarification or add additional context in comments.

1 Comment

have you added any child?
0

You need to add required=False to your nested ChildSerializer:

class ParentSerializer(ModelSerializer):
    children = ChildSerializer(many=True, required=False)
    class Meta:
        model = Parent
        fields = ('name','children')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.