Reputation: 833
I'm searching how to write one serializer like: Using GET -> I give 'uuid' -> server response is only 'name', 'content', 'rating' Using POST -> I give 'name', 'content', 'rating' -> serer response is just created 'uuid' and 'time'.
This is my learning model:
class Post(models.Model):
uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=40)
time = models.DateTimeField()
content = models.TextField(max_length=250)
rating = models.IntegerField(default=1)
I was learning how to create Django REST API from youtube, and 'teacher' said that it's better to make one serializer for different actions like when "POST" method you get 'uuid' and 'time', but when "GET" method you get 'name', 'time', 'content' and 'rating'. But on this lesson he want to show it easier way, so he made two serialisers, depends on method:
class PostGetSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = [
'name',
'time',
'content',
'rating'
]
class PostCreateSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = [
'uuid',
'time',
]
I know it is just a small example but I hope you get it.
How can I manipulate request and response data of ONE serializer depends on method?
EDITED becouse I think It is not clear:
I want something like this:
When I'm creating object via API initial JSON data is 'name', 'content' and 'rating'... after this creating request, object was created with pk -> uuid and auto time, and json data. I want to get response 'uuid' field (pk) and 'time' field (auto time).
But when I'm using GET with header 'uuid' (to get specyfic object) in response I want to have 'name', 'content', 'rating', and 'time' without 'uuid'.
All in one serializer. Is it even possible? What type of writing serializers is commonly used by programmers? For each method one serializer? or one big specific serializer for one model.
Upvotes: 0
Views: 4824
Reputation: 2109
Use only 1 serializer set the fields that you want the system to populate to be read only. http://www.django-rest-framework.org/api-guide/serializers/#specifying-read-only-fields
Include the UUID field always, even when requesting by the ID. It doesn't really hurt the response and it makes sure each entity is consistent when/where you are requesting it.
Upvotes: 2