Field Based Permission Django Rest Framework

Some case, I have to add permission on some fields on my model that to be published in my REST API.

from rest_framework import serializers

class PrivateField(serializers.Field):

    def get_attribute(self, obj):
        return obj

    def to_representation(self, obj):
        """ Check whether user authenticated or not before represent private
        field and show empty string if the user not authenticated. """

        # Get meta fields form model class instance.
        meta = self.context['view'].model._meta
        is_relation = meta.get_field(self.field_name).is_relation

        if self.context['request'].user.is_authenticated():
            result = getattr(obj, self.field_name)
            if is_relation:  # check if relation field.
                return result.pk
            return result
        else:
            # Because foreign key returned ID, so if the user unauthorized
            # to see the data then display -1, otherwise display empty string.
            if is_relation:
                return -1
            return ""

Then, what you need to do is just apply “PrivateField” to your serializer.

class MySerializer(serializers.ModelSerializer):
    private_field1 = PrivateField()
    private_field2 = PrivateField()

    class Meta:
        model = MyModel

Update 4 January 2014:
Hi, i updated how to get relationship in python code referred from this presentation.
Reference: http://stackoverflow.com/a/32302088/1936697

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s