Skip to content

Instantly share code, notes, and snippets.

@grillazz
Created September 24, 2019 09:29
Show Gist options
  • Save grillazz/89b0bca72e9770d445148937f26ea89d to your computer and use it in GitHub Desktop.
Save grillazz/89b0bca72e9770d445148937f26ea89d to your computer and use it in GitHub Desktop.
DRF overwriting __init__ for Serializer to conditionally add fields.
from rest_framework.serializers import HyperlinkedModelSerializer
from dry_rest_permissions.generics import DRYPermissionsField
from .models import CustomUser
class CustomUserSerializer(HyperlinkedModelSerializer):
permissions = DRYPermissionsField(additional_actions=["activate", "deactivate"])
class Meta:
model = CustomUser
fields = ("url", "id", "name", "email", "permissions", "role", "is_active")
# non admin should't be able to update role and is_active
read_only_fields = ["role", "is_active"]
class ForAdminCustomUserSerializer(CustomUserSerializer):
class Meta:
model = CustomUser
fields = ("url", "id", "name", "email", "permissions", "role", "is_active")
def __init__(self, *args, **kwargs):
super(CustomUserSerializer, self).__init__(*args, **kwargs)
# get the request from parent serializer's context
request_obj = self.context.get('request')
# add extra fields if user is admin
if request_obj.user.role == 'ADMIN':
self.Meta.fields = list(self.Meta.fields)
self.Meta.fields.extend(["role", "is_active"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment