How can I modify the Serializer filed of django restframework ModelSerializer when use it in view.py?

huangapple go评论73阅读模式
英文:

How can I modify the Serializer filed of django restframework ModelSerializer when use it in view.py?

问题

这是我的DRF序列化器:

class TranMetaSerializer(serializers.ModelSerializer):
    class Meta:
        model = TranMeta
        fields = "__all__"

当我在view.py中使用序列化器时,我想通过request.GET来更改字段:

@api_view(["GET"])
def getTran_all(request, formar=None):
    fields = request.GET.get("fields")
    if fields:
        fields = fields.split(",")
        data = TranMeta.objects.order_by("data_id").values(*fields)
    else:
        fields = "__all__"
        data = TranMeta.objects.all()
    serializer = TranMetaSerializer(data, many=True)

但上面的代码会引发一个错误,错误信息是"Field.init() got an unexpected keyword argument 'fields'"。那么我该如何实现我的目标呢?

英文:

This is my DRF serializer:

class TranMetaSerializer(serializers.ModelSerializer):
  class Meta:
    model = TranMeta
    fields = "__all__"

And when i use the serializer in view.py, i want to change the filed via request.get filed:

@api_view(["GET"])
def getTran_all(request, formar=None):
    fields = request.GET.get("fields")
    if fields:
        fields = fields.split(",")
        data = TranMeta.objects.order_by("data_id").values(*fields)
    else:
        fields = "__all__"
        data = TranMeta.objects.all()
    serializer = TranMetaSerializer(data, many=True, fields=fields)

But the code above raise an error which says "Field.init() got an unexpected keyword argument 'fields'"
So what can i do to achieve my goal?

答案1

得分: 2

我建议您使用DRF中提供的动态字段序列化器。

class TranMetaSerializer(serializers.ModelSerializer):
    class Meta:
        model = TranMeta
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        # 不要将 'fields' 参数传递给超类
        fields = kwargs.pop('fields', None)

        # 正常实例化超类
        super().__init__(*args, **kwargs)

        if fields is not None:
            # 删除未在 'fields' 参数中指定的任何字段
            allowed = set(fields)
            existing = set(self.fields)
            for field_name in existing - allowed:
                self.fields.pop(field_name)
英文:

I recommend you to use a dynamic fields serializer available in DRF

class TranMetaSerializer(serializers.ModelSerializer):
  class Meta:
    model = TranMeta
    fields = "__all__"

  def __init__(self, *args, ***kwargs):
    # Don't pass the 'fields' arg up to the superclass
    fields = kwargs.pop('fields', None)

    # Instantiate the superclass normally
    super().__init__(*args, **kwargs)

    if fields is not None:
        # Drop any fields that are not specified in the `fields` argument.
        allowed = set(fields)
        existing = set(self.fields)
        for field_name in existing - allowed:
            self.fields.pop(field_name)

huangapple
  • 本文由 发表于 2023年7月6日 17:40:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76627487.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定