Trying to learn DRF coming from the node.js world and I’m really stuck on serializers and model serializers. It’s like one class that does both schema validation and creating / updating models too. I feel I should be making one serializer for creating objects and another serializer to define a specific output.
In my test project I have a simple Posts and Comments model, each Comment is attached to a Post and a User has many posts (pretty basic data model). What serializers should I create for this? I was thinking:
- PostDetailSerializer:
class PostDetailSerializer(serializers.ModelSerializer):
author = UserSerializer(read_only=True)
comments = CommentSerializer(read_only=True, many=True, required=False)
class Meta:
model = models.Post
fields = ['uuid', 'text', 'author', 'comments', 'pins', 'date_created']
read_only_fields = ['uuid', 'pins', 'date_created']
- CommentSerializer:
class CommentSerializer(serializers.ModelSerializer):
author = UserSerializer(read_only=True)
post = serializers.SlugRelatedField(slug_field='uuid', read_only=True)
class Meta:
model = models.Comment
fields = ['uuid', 'text', 'date_created', 'post', 'author']
read_only_fields = ['date_created', 'uuid']
But then I’m confused about how I protect the updating of the fields. Like I don’t want to just run is_valid
and then save
because then a user would be able to add a comment as another user right?