Modify ModelSerializer to support per-action field configuration #6842
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
This loosely Refs #4632 but they asked for per-action serializer configuration in ViewSets, however this PR implements a per-action serializer, so the ViewSet would just include one serializer. But this would resolve the underlying problem there.
The general idea is that this PR modifies the
ModelSerializer
to use a new attribute on theMeta
class,action_fields
.action_fields
is a dictionary of strings that represent actions, and under the action is a dictionary offields
,exclude
, andextra_kwargs
, that work just like theMeta
attributes, except they override the default serializer behavior for that particular action. The previous workaround was to override theget_serializer_class
method and use the action to decide which serializer you want to use.The nice thing about this is that it is backward compatible (everything works the same if you don't have the
action_fields
attribute), and it means you don't have to build multiple serializers. I noticed that when building multiple serializers for the same model, a lot of logic would be duplicated and it wasn't very DRY.I did put all this functionality into a 3rd party package at https://github.com/gregschmit/drf-action-serializer, but since it ended up being such a small and backwards compatible change, I decided to see if the DRF community wanted to just pull it into the project.
Also, I did write tests and added a section to the documentation, however this is my first PR for this project and I'm very new to contributing to big open source projects, so please let me know if any of the code/tests/docs that I wrote are crap.