Reputation: 11
I have models.py like this:
class Tasks(models.Model):
id = models.AutoField(primary_key=True)
roles = (
(u'1', u'task1'),
(u'2', u'task2'),
)
role = models.CharField(max_length=1, choices=roles, default='1')
Then I have serializers.py looking like this:
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Tasks
fields = '__all__'
My viewset looks like this:
class Tasks(viewsets.ModelViewSet):
queryset = Tasks.objects.all()
serializer_class = TaskSerializer
So what I want to do is; say when I make a POSt request; I want to return saved data for tasks roles; if a I save it as 1, instead of returning roles field as 1, I want to return task1. How do I do this?
Upvotes: 1
Views: 645
Reputation: 88519
You can override to_representation()
method in Serializer class
as below,
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Tasks
fields = '__all__'
def to_representation(self, instance):
return_dict = dict(super().to_representation(instance))
if self.context.get('view').action == 'create' and return_dict:
choice_dict = {k[0]: k[1] for k in instance.roles}
return_dict['role'] = choice_dict[return_dict['role']]
return return_dict
Short Description
Here self.context.get('view').action == 'create'
will check whether the view's action is a create
(simplym, a POST
request or not) or not.
So the output response for a create
operation be like this,
{
"id": 3,
"role": "task2"
}
Why did I do a type casting to dict
?
to_representaion()
method return a OrderedDict()
which is immutable object.
Upvotes: 1