通过ViewSet覆盖Django Rest Framework序列化器中的“all_fields”属性

1zmg4dgp  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(125)

我正在尝试使用基于类的方法在DRF中构建一个API端点。
下面是Viewset和Serializer文件中的代码片段。
organization_viewset.py:

class organizationViewSet(viewsets.ViewSet):

    def list(self, request):
        organizations = get_all_organizations(op_format="OBJECT")
        org_serializer = OrganizationSerializer(organizations, many=True)
        return Response(org_serializer.data)

organization_serializer.py:

from rest_framework import serializers
from Home.models.organization import Organization

class OrganizationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Organization
        fields = '__all__'

接下来我想做的是,在创建OrganizationSerializer的示例时,我想传递一个参数如下:

org_serializer = OrganizationSerializer(organizations, many=True, all_fields=False)

如果all_fields值为True,那么我希望序列化程序返回所有字段。否则序列化程序将返回以下字段。

fields = ('id','orgName', 'orgAltName', 'orgPlant', 'orgAddress1')

为了解决这个问题,我尝试用选定的字段编写第二个序列化器类。但是,我更喜欢使用单个序列化程序类在选定字段和所有字段之间切换。

kxeu7u2r

kxeu7u2r1#

Django

我认为你可以很容易地做到这一点。
首先阅读这里:

your_serializer = OrganizationSerializer()
your_serializer.serialize(queryset)
data = your_serializer.getvalue()

这可能是使用序列化程序获取数据的“正常”方式。
可以将fields参数传递给.serialize()方法。阅读这里:

wanted_fields = ('id','orgName', 'orgAltName', 'orgPlant', 'orgAddress1')

your_serializer = OrganizationSerializer()
your_serializer.serialize(queryset, fields=wanted_fields)
data = your_serializer.getvalue()

它应该只序列化指定的字段。

Django REST API

在这里找到您的用例

class DynamicFieldsModelSerializer(serializers.ModelSerializer):
    """
    A ModelSerializer that takes an additional `fields` argument that
    controls which fields should be displayed.
    """

    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)

class OrganizationSerializer(DynamicFieldsModelSerializer):
    class Meta:
        model = Organization
        fields = '__all__'
class organizationViewSet(viewsets.ViewSet):

    def list(self, request):
        fields = ('orgAltName', 'orgPlant', 'orgAddress1')
        organizations = get_all_organizations(op_format="OBJECT")
        org_serializer = OrganizationSerializer(organizations, fields=fields, many=True)
        return Response(org_serializer.data)

相关问题