Dynamically include or exclude Serializer class fields

后端 未结 3 638
名媛妹妹
名媛妹妹 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:39

    This answer comes late but for future google searches: there is an example in the documentation about Dynamically modifying fields. So, by passing an argument to the serializer, you control whether or not a field is processed:

    serializer = MyPostSerializer(posts, show_email=permissions)
    

    and then in the init function in the serializer you can do something like:

    class MyPostSerializer(serializers.ModelSerializer):
    
    def __init__(self, *args, **kwargs):
        show_email = kwargs.pop('show_email', None)
    
        # Instantiate the superclass normally
        super(DeviceSerializer, self).__init__(*args, **kwargs)
    
        if not show_email:
            self.fields.pop("show_email")
    

    Now the show_email field will be ignored by the serializer.

提交回复
热议问题