Implementing field-level permissions using DRF

327 views
Skip to first unread message

Chitharanjan Das

unread,
Jan 8, 2016, 9:35:16 AM1/8/16
to Django REST framework
A given resource Thingy may be accessed by 3 kinds of users:
  • Alpha Users: Have write access on all fields.
  • Beta Users: Do not have write access on all fields, but *may* have read access on those fields.
  • Gamma Users: Do not have any write access.
First off, what would be the best way to achieve this using DRF?


I'm currently thinking of writing multiple permission-based ModelSerializers, each with its own values for fields, exclude and read_only_fields. Like so:

from rest_framework import serializers

from models import Thingy


class ThingySerializerForAlphas(serializers.ModelSerializer):
   
class Meta:
        model
= Thingy
        fields
= '__all__'


class ThingySerializerForBetas(serializers.ModelSerializer):
   
class Meta:
        model
= Thingy
        fields
= ('field_1', 'field_2', 'field_3')
        read_only_fields
= ('field_1', )


class ThingySerializerForGammas(serializers.ModelSerializer):
   
class Meta:
        model
= Thingy
        fields
= ('field_1', 'field_2',)
        read_only_fields
= ('field_1', 'field_2')


and later in my views, based on the permissions on request.user, I could plug in the correct serializer to use. However, I don't want to have to repeat this logic involving picking the correct Serializer in each of my views.

So my second question is (given this approach is feasible), is there a ViewSet method that always gets called prior to list(), create(), update(), destroy(), etc., that I can hook this serializer selection logic into?

Chitharanjan Das

unread,
Jan 8, 2016, 10:01:59 AM1/8/16
to Django REST framework
I believe I've found my answer in the get_serialized_class() method.
Reply all
Reply to author
Forward
0 new messages