I am new at Django and couldn't find solution for my problem.
The problem is to force specific serializer for include different amount of fields in case of utilizing different views. I would like to use 'id' field in my 1st view, and in 2nd view - 'id' and 'name' fields.
Here is my model.py
class Processing(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField()
description = models.CharField()
And here is my serializer.py
class ProcessingSerializer(serializers.ModelSerializer):
id = serializers.ModelField(model_field=Processing()._meta.get_field('id'))
class Meta:
model = Processing
fields = ('id', 'name')
Any help will be welcome.
You can also use the next approach:
Then add this mixin to your ViewSet:
But if you need a Serializer with a dynamic set of fields (ex. you have a handler but you need to return only specific fields in the response), you can use the approach from Ykh's answer.
https://stackoverflow.com/a/44064046/2818865
When someone just starts using DRF, a common mistake is to try to make the same Serializer do everything under the sun. Certainly I went down that path myself.
but life becomes a lot simpler when you use mutiple serializers for different tasks. You can easily switch serializers using the get_serializer_class method. Here is an example right from the manual that shows how to use one for admins and another for ordinary users
Sometimes you want to use a single serializer for lists and another one for when providing details. Try something like this:
Life is much simpler this way.
use:
or