django-rest-framework serializer different fields in multiple views

前端 未结 3 745
没有蜡笔的小新
没有蜡笔的小新 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:08

    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

    def get_serializer_class(self):
        if self.request.user.is_staff:
            return FullAccountSerializer
        return BasicAccountSerializer
    

    Sometimes you want to use a single serializer for lists and another one for when providing details. Try something like this:

    def get_serializer_class(self):
        if self.action == 'retrieve':
            return serializers.PlayerDetailSerializer
        else : 
            return serializers.PlayerSerializer
    

    Life is much simpler this way.

提交回复
热议问题