django-rest-framework serializer different fields in multiple views

前端 未结 3 749
没有蜡笔的小新
没有蜡笔的小新 2021-02-08 02:41

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 di

3条回答
  •  孤街浪徒
    2021-02-08 03:12

    You can also use the next approach:

    class SelectSerializerMixin(object):
        serializer_class = None
        list_serializer_class = None
        retrieve_serializer_class = None
        update_serializer_class = None
        partial_update_serializer_class = None
        create_serializer_class = None
    
        def get_serializer_class(self):
            """
            Return the class to use for the serializer.
            Defaults to using `self.serializer_class`.
            """
            assert self.serializer_class is not None, (
                "'%s' should either include a `serializer_class` attribute, "
                "or override the `get_serializer_class()` method."
                % self.__class__.__name__
            )
            return getattr(self, f"{self.action}_serializer_class") or self.serializer_class
    

    Then add this mixin to your ViewSet:

    class MyModelViewSet(SelectSerializerMixin, ModelViewSet):
        queryset = models.MyModel.objects.all()
        serializer_class = serializers.SomeSerializer
        retrieve_serializer_class = serializers.AnotherSerializer
        list_serializer_class = serializers.OneMoreSerializer
    

    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

提交回复
热议问题