【问题标题】:How to dynamically remove fields from serializer output如何从序列化器输出中动态删除字段
【发布时间】:2016-10-25 10:21:11
【问题描述】:

我正在使用 Django Rest 框架开发 API,我想从序列化程序中动态删除字段。问题是我需要根据另一个字段的值删除它们。我怎么能那样做? 我有一个像这样的序列化程序:

class DynamicSerliazer(serializers.ModelSerializer):
    type = serializers.SerializerMethodField()
    url = serializers.SerializerMethodField()
    title = serializers.SerializerMethodField()
    elements = serializers.SerializerMethodField()

    def __init__(self, *args, **kwargs):
        super(DynamicSerliazer, self).__init__(*args, **kwargs)
        if self.fields and is_mobile_platform(self.context.get('request', None)) and "url" in self.fields:
            self.fields.pop("url")

如您所见,我已经删除了“url”字段,具体取决于请求是否来自移动平台。但是,我想根据“类型”值删除“元素”字段。我该怎么做?

提前致谢

【问题讨论】:

    标签: django-rest-framework django-serializer


    【解决方案1】:

    可以通过覆盖序列化程序中的to_representation() 方法来customize the serialization behavior

    class DynamicSerliazer(serializers.ModelSerializer):
    
        def to_representation(self, obj):
            # get the original representation
            ret = super(DynamicSerializer, self).to_representation(obj)
    
            # remove 'url' field if mobile request
            if is_mobile_platform(self.context.get('request', None)):
                ret.pop('url')
    
            # here write the logic to check whether `elements` field is to be removed 
            # pop 'elements' from 'ret' if condition is True
    
            # return the modified representation
            return ret 
    

    【讨论】:

      【解决方案2】:

      您可以创建多个序列化程序并在视图中选择合适的一个

      class IndexView(APIView):
          def get_serializer(self):
              if self.request.GET['flag']:
                  return SerializerA
              return SerializerB
      

      使用继承使序列化程序 DRY。

      【讨论】:

      • 从今天开始,如果您使用 get_serializer_class 而不是 get_serializer,这将有效。
      【解决方案3】:

      我的问题和你的有点相似,我通过继承解决了。

      class StaticSerializer(serializers.ModelSerializer):
      
          class Meta:
              model = StaticModel
              fields = (
                  'first_name', 'last_name', 'password', 'username',
                  'email'
              )
      
      
      class DynamicSerializer(StaticSerializer):
      
          class Meta:
              model = StaticModel
              fields = (
                  'first_name',
              )
      

      【讨论】:

      • 这很好,但不是动态的。
      猜你喜欢
      • 2012-07-08
      • 2017-06-01
      • 2011-01-31
      • 1970-01-01
      • 2015-07-02
      • 1970-01-01
      • 1970-01-01
      • 2010-12-09
      • 2018-12-24
      相关资源
      最近更新 更多