Logo

dev-resources.site

for different kinds of informations.

Excluding Fields in Django Rest Framework Serializers

Published at
1/13/2022
Categories
django
webdev
drf
python
Author
timmytango
Categories
4 categories in total
django
open
webdev
open
drf
open
python
open
Author
10 person written this
timmytango
open
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.

drf Article's
30 articles in total
Favicon
Djoser+SimpleJWT
Favicon
AssertionError: 403
Favicon
extra_kwargs arguments
Favicon
To Django or to DjangoREST?
Favicon
Django API | queryset & object, filter() & get()
Favicon
I just tried to compare values between model and serializer
Favicon
Customize Schema with @extend_schema_view
Favicon
Seperate serializers
Favicon
Leveraging Headers for Dynamic Localization in Django
Favicon
Django REST Framework warning: `UnorderedObjectListWarning`
Favicon
DRF create @property decorator in view and use property in serializer
Favicon
why Serializers used for? easy to understand
Favicon
Async API Calls Unleashed: Exploring Django 4 and Django Rest Framework
Favicon
# Comprehensive Security for Class-Based Views in Django Rest Framework
Favicon
HATEOAS Principle - Generating Full Paths for Objects in Django Rest Framework.
Favicon
Instance version control in DRF with Django Reversion
Favicon
Django News #171 - DjangoCon US 2023 Preview
Favicon
How to create thumbnails programmatically in Django
Favicon
Automatically Add Logged In User Under 'created_by' and 'updated_by' to Model in Django Rest Framework
Favicon
how to fix raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
Favicon
CSRF verification failed. Request aborted. in django rest framework
Favicon
CSRF verification failed. Request aborted. in django rest framework
Favicon
How to fix "Must supply api_key"
Favicon
Updating A Many-To-Many Relationship In Django
Favicon
Excluding Fields in Django Rest Framework Serializers
Favicon
JWT Authentication with Django REST Framework - What? Why? How?
Favicon
How to implement Auto Expiring Token in Django Rest Framework
Favicon
Building web applications with Django, Django REST Framework and Nuxt
Favicon
How to use Postman to authenticate to Django Rest Framework
Favicon
Setting Up Django Rest Framework

Featured ones: