DEV Community

Tim Bennett
Tim Bennett

Posted on • Originally published at timmytango.com

4 2

Excluding Fields in Django Rest Framework Serializers

This is a simple way to exclude fields from being returned by a DRF serializer, without creating a separate serializer or installing another package. I needed to exclude a field when using the list action for a ModelViewSet, but because we'll be utilizing the serializer's context, it can be used no matter how you write your views.

Modifying the serializer

We're going to override the serializer's get_fields method to remove any fields we pass through the serializer's context. I like to use a list of strings so that I can easily remove fields without making changes to the serializer later.

class WidgetSerializer(serializers.Serializer):
    name = SomeTypeOfField()
    parts = SomeTypeOfField()

    def get_fields(self):
        fields = super().get_fields()

        exclude_fields = self.context.get('exclude_fields', [])
        for field in exclude_fields:
            # providing a default prevents a KeyError
            # if the field does not exist
            fields.pop(field, default=None)

        return fields
Enter fullscreen mode Exit fullscreen mode

You would use the same method with a ModelSerializer if you use those.

How to use

Let's assume we have a field named parts in WidgetSerializer that we'd like to exclude from our response in a specific view. All we have to do is include the field name in the exclude_fields list passed through the serializer's context.

class ListWidgets(APIView):
    def get(self, request, format=None):
        context = {
            'exclude_fields': [
                'parts'
            ]
        }

        widgets = Widget.objects.all()
        serializer = WidgetSerializer(widgets, many=True, context=context)

        # parts field will not be included
        return Response(serializer.data) 
Enter fullscreen mode Exit fullscreen mode

If you are using DRF's ViewSets (including ModelViewSet), you can override the get_serializer_context method instead. For example, if you only wanted to exclude fields in the list action, you could do the following:

class WidgetViewSet(viewsets.ModelViewSet):
    queryset = Widget.objects.all()
    serializer_class = WidgetSerializer

    def get_serializer_context(self):
        context = super().get_serializer_context()
        if self.action == 'list':
            context['exclude_fields'] = ['parts']
        return context
Enter fullscreen mode Exit fullscreen mode

Conclusion

Hopefully this little guide helps you easily exclude fields from DRF serializers. I've only tested it with ModelViewSets and excluding fields in the list action, so it may not cover all cases. Feel free to contact me with corrections or suggestions on improvements.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more