About Context-aware Serializer Fields
When using Django REST Framework, you can conditionally remove fields from serializers in the to_representation()
method, for example:
# 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
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.