Hide Password from Django Serializer when using Depth

Hide password or sensitive information when using Django depth functionality in Django Rest Framework Serializer.
A corgi smiling happily

There are times when you create an API with user in it and then when you wanna need more details, you set depth of the API and to the surprise you see some confidential fields in it. First in User serializer (or in serializer in which you wanna hide fields) you need to exclude those fields.

1from django.contrib.auth import get_user_model
2from rest_framework import serializers
4class UserSerializer(serializers.ModelSerializer):
5 class Meta:
6 model = get_user_model()
7 exclude = ['password', 'last_login', 'is_superuser', 'is_staff',
8 'is_active', 'date_joined', 'groups', 'user_permissions']

And when you want to include user into another serializer, instead of using PrimaryRelated or StringRelated or any other, use that serializer directly, like follows:

1from mymasters.models.Course import Course
2from mymasters.serializers.UserSerializer import UserSerializer
3from rest_framework import serializers
5class CourseSerializer(serializers.ModelSerializer):
6 teacher = UserSerializer()
8 class Meta:
9 model = Course
10 fields = '__all__'
11 depth = 1


Do you have any questions, or simply wish to contact me privately? Don’t hesitate to shoot me a DM on Twitter.

Have a wonderful day.
Abhishek 🙏

Subscribe to my newsletter

Get email from me about my ideas, full-stack development resources, tricks and tips as well as exclusive previews of upcoming articles.

No spam. Just the highest quality ideas you’ll find on the web.