0
0
Djangoframework~10 mins

Nested serializers in Django - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the serializer base class.

Django
from rest_framework import [1]
Drag options to blanks, or click blank then click option'
Amodels
Bserializers
Cviews
Dfields
Attempts:
3 left
💡 Hint
Common Mistakes
Importing models instead of serializers
Using views instead of serializers
2fill in blank
medium

Complete the code to define a nested serializer field.

Django
class BookSerializer(serializers.ModelSerializer):
    author = [1](read_only=True)

    class Meta:
        model = Book
        fields = ['title', 'author']
Drag options to blanks, or click blank then click option'
AIntegerField
BCharField
CSerializerMethodField
DAuthorSerializer
Attempts:
3 left
💡 Hint
Common Mistakes
Using CharField instead of a serializer for nested data
Using SerializerMethodField without defining the method
3fill in blank
hard

Fix the error in the nested serializer to allow writing nested data.

Django
class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = ['name']

class BookSerializer(serializers.ModelSerializer):
    author = AuthorSerializer([1]=True)

    class Meta:
        model = Book
        fields = ['title', 'author']
Drag options to blanks, or click blank then click option'
Arequired
Bwrite_only
Cmany
Dread_only
Attempts:
3 left
💡 Hint
Common Mistakes
Setting read_only=True disables writing nested data
Using many=True when the relation is not multiple
4fill in blank
hard

Fill both blanks to correctly override the create method for nested data.

Django
class BookSerializer(serializers.ModelSerializer):
    author = AuthorSerializer()

    def create(self, validated_data):
        author_data = validated_data.pop([1])
        author = Author.objects.create([2])
        book = Book.objects.create(author=author, **validated_data)
        return book
Drag options to blanks, or click blank then click option'
A'author'
Bauthor_data
Cvalidated_data
D'book'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong key to pop nested data
Passing wrong data to create method
5fill in blank
hard

Fill all three blanks to correctly override the update method for nested serializers.

Django
class BookSerializer(serializers.ModelSerializer):
    author = AuthorSerializer()

    def update(self, instance, validated_data):
        author_data = validated_data.pop([1])
        author = instance.author
        author.name = author_data.get([2], author.name)
        author.save()
        instance.title = validated_data.get([3], instance.title)
        instance.save()
        return instance
Drag options to blanks, or click blank then click option'
A'author'
B'name'
C'title'
D'author_data'
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect keys for nested data
Not saving updated instances