-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
Add Serializer per action to ViewSets #4632
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
This might relate to #2062, and even be a partial solution for that issue. |
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. |
@soulhunter1987 That solution is a bit more complex than what I'd like to see (and suggested). |
I'd like to see someone tackle this as a third party mixin class rather than bringing in anything else to core right now. |
Hey @tomchristie, I wrote something that I think fixes this (drf-action-serializer) but rather than making a new ViewSet, I created a |
@tomchristie I am considering opening a pull request to pull this functionality into the |
IMO, I'd like to show Data structure. |
A common use case is to list objects first, and then retrieve details.
The current implementation of
ViewSet
is to use oneSerializer
for every action (list
,retrieve
, etc).This means listing and then retrieving yields no additional data.
A good solution would be to allow a default
Serializer
(using theserializer_class
attribute of aViewSet
), and an optional dict of action toSerializer
, as described in this StackOverflow answer:http://stackoverflow.com/a/22922156/117831
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.
The text was updated successfully, but these errors were encountered: