Question:
Implement nested serializers in the Django rest framework

Problem:

I'm trying to implement nested serializers.


Serializers.py

class BranchSerializer(serializers.ModelSerializer):


    class Meta:

        model = Branch

        fields = '__all__'


class StudentSerializer(serializers.ModelSerializer):


    class Meta:

        model = Student

        fields = '__all__'



to override branch in studentserializers and import branch details.


Solution:

class BranchSerializer(serializers.ModelSerializer):

    class Meta:

        model = Branch

        fields = '__all__'


class StudentSerializer(serializers.ModelSerializer):


    branch = serializers.PrimaryKeyRelatedField(queryset=Branch.objects.all())


    # to get single field name.

    # branch = serializers.CharField(source = 'branch.branch_name') 


    class Meta:

        model = Student

        fields = '__all__'



Suggested blogs:

>How to read frame from ffmpeg subprocess in Python?

>How to register a schedule with the controller?

>How to resolve the Composer dependency conflicts (Symfony)?

>How to route between different components in React.js?

>How to save python yaml and load a nested class?-Python

>How to send multiple HTML form fields to PHP arrays via Ajax?


Ritu Singh

Ritu Singh

Submit
0 Answers