Bird
0
0

Given this model and serializer, what will serializer.data output?

medium📝 component behavior Q4 of 15
Django - REST Framework Basics
Given this model and serializer, what will serializer.data output?
class Author(models.Model):
    name = models.CharField(max_length=100)

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

author = Author(name='Alice')
serializer = AuthorSerializer(author)
A{'name': 'Alice'}
B{'author': 'Alice'}
C{'name': None}
DRaises an error because author is not saved
Step-by-Step Solution
Solution:
  1. Step 1: Understand serializer.data output

    serializer.data returns a dictionary with the fields specified, here 'name' with value 'Alice'.
  2. Step 2: Consider instance state

    Even if the instance is not saved, serializer reads the attribute value directly.
  3. Final Answer:

    {'name': 'Alice'} -> Option A
  4. Quick Check:

    serializer.data outputs field dict = A [OK]
Quick Trick: serializer.data shows model fields as dict, even unsaved [OK]
Common Mistakes:
MISTAKES
  • Expecting error if instance not saved
  • Wrong key name in output
  • Assuming None values if unsaved

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes