Search code examples
pythondjangodjango-rest-frameworkdjango-serializerdrf-queryset

DRF: How to hide the password in serializers that use the depth option?


I'm using the below serializer for the User model, but when I use depth for handling foreign keys, the password shows in the User object.

User serializer:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        read_only_fields = ('is_active', 'is_staff', 'is_superuser',)
        exclude = ('password', )
        extra_kwargs = {'password': {'write_only': True, 'min_length': 4}}

In below serializer everything is fine:

class AuditSerializer(serializers.ModelSerializer):
    def __init__(self, instance=None, **kwargs):
        if instance:
            setattr(self.Meta, 'depth', 10)
        else:
            setattr(self.Meta, 'depth', 0)
        super(AuditSerializer, self).__init__(instance, **kwargs)

    initiator = UserSerializer(read_only=True)

    class Meta:
        model = Audit
        fields = ['id', 'initiator']
        read_only_fields = ['id', 'initiator']
        depth = 0

But in the below that has relation to the previous model/serializer, I have the password issue:

class AuditAttachmentSerializer(serializers.ModelSerializer):
    def __init__(self, instance=None, **kwargs):
        if instance:
            setattr(self.Meta, 'depth', 10)
        else:
            setattr(self.Meta, 'depth', 0)
        super(AuditAttachmentSerializer, self).__init__(instance, **kwargs)

    class Meta:
        model = AuditAttachment
        fields = ['id', 'audit']
        read_only_fields = ['id']
        depth = 0

Solution

  • I delete the __init__ method and changed it to the below solution.

    DRF: Simple foreign key assignment with nested serializers?