Django Rest Framework: Dynamically return subset of fields

后端 未结 8 725
南笙
南笙 2020-11-28 18:16

Problem

As recommended in the blogpost Best Practices for Designing a Pragmatic RESTful API, I would like to add a fields query parameter to a Django R

8条回答
  •  旧时难觅i
    2020-11-28 19:02

    You can override the serializer __init__ method and set the fields attribute dynamically, based on the query params. You can access the request object throughout the context, passed to the serializer.

    Here is a copy&paste from Django Rest Framework documentation example on the matter:

    from rest_framework import serializers
    
    class DynamicFieldsModelSerializer(serializers.ModelSerializer):
        """
        A ModelSerializer that takes an additional `fields` argument that
        controls which fields should be displayed.
        """
    
        def __init__(self, *args, **kwargs):
            # Instantiate the superclass normally
            super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
    
            fields = self.context['request'].query_params.get('fields')
            if fields:
                fields = fields.split(',')
                # Drop any fields that are not specified in the `fields` argument.
                allowed = set(fields)
                existing = set(self.fields.keys())
                for field_name in existing - allowed:
                    self.fields.pop(field_name)
    
    
    class UserSerializer(DynamicFieldsModelSerializer, serializers.HyperlinkedModelSerializer):
    
        class Meta:
            model = User
            fields = ('url', 'username', 'email')
    

提交回复
热议问题