About Context-aware Serializer Fields

When using Django REST Framework, you can conditionally remove fields from serializers in the to_representation() method, for example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# accounts/serializers.py
from rest_framework import serializers
from .models import User

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ["first_name", "last_name", "email"]

    def to_representation(self, instance):
        values = super().to_representation(instance=instance)

        if not self.context["request"].user.is_staff:
            values.pop("email")

        return values

Tips and Tricks Programming Development Django 5.x Django 4.2 Django 3.2 Django REST Framework