Dynamically include or exclude Serializer class fields

后端 未结 3 642
名媛妹妹
名媛妹妹 2021-02-09 05:56

In my User profile model I\'ve included a show_email field explicitly. So, to add this feature to my API, the UserSerializer class looks like this:

3条回答
  •  一生所求
    2021-02-09 06:43

    You could do this in your API view by overriding the method returning the response, i.e. the "verb" of the API view. For example, in a ListAPIView you would override get():

    class UserList(generics.ListAPIView):
        model = django.contrib.auth.get_user_model()
        serializer_class = UserSerializer
    
        def get(self, request, *args, **kwargs):
            response = super(UserList, self).get(request, *args, **kwargs)
            for result in response.data['results']:
                if result['email'] is None:
                    result.pop('email')
            return response
    

    You would probably want to add some more checking for attributes, but that's the gist of how it could be done. Also, I would add that removing fields from some results may cause issues for the consuming application if it expects them to be present for all records.

提交回复
热议问题