Join GitHub today
GitHub is home to over 36 million developers working together to host and review code, manage projects, and build software together.Sign up
Add Serializer per action to ViewSets #4632
A common use case is to list objects first, and then retrieve details.
The current implementation of
This means listing and then retrieving yields no additional data.
A good solution would be to allow a default
Note: I am not the author of this answer and code, this is just an answer to a problem I have with DRF, and I think it's worth looking at this as an enhancement.
Yes, the problem is very actual. Currently I have to create a new serializer per any viewset action, because serializer fields most of the time differ for each method:
And then configure an appropriate serializer to be used for certain viewset actions. Suggested approach would make it easier than now, but I would advise a little bit different way:
Allow to configure several lists of fields in the serilizer. For example:
class MyModelSerializer(serializers.ModelSerializer): class Meta: list_fields: [...], retrieve_fields: [...], create_fields: [...] fields: [...] # default fallback
Fields here are specified as "viewset action"_fields. So appropriate fields will be invoked for viewset actions.
class MyModelSerializer(serializers.ModelSerializer): relation_obj = RelationSerializer(model_field='relation', action='list') class Meta: list_fields: ['relation_obj', 'relation'], retrieve_fields: ['relation', ...], create_fields: ['relation', ...] fields: [...] # default fallback
In this example list action will return "relation" primary key and the whole "relation_obj" object, as specified in RelationSerializer "list_fields" meta property.