1
\$\begingroup\$

I have a Profile object with two fields. One is safe for the public to see, while the other contains private data.

class Profile(models.Model):
    owner = models.OneToOneField(User) #django.contrib.auth.models
    public_field = models.TextArea()
    private_field = models.TextArea()

I have two DjangoRestFramework serializers for this model:

class BasicProfileSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Profile
        fields = ('url', 'owner', 'public_field')

class FullProfileSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Profile
        fields = ('url', 'owner', 'public_field', 'private_field')
        read_only_fields = ('owner',)

Lastly, I have a ModelViewSet for this object. Here, I would like to always use the BasicProfileSerializer for list and create actions. For all other actions, I would like to use the FullProfileSerializer only if the user making the request is_staff or is the owner of the Profile object.

class ProfileViewSet(viewsets.ModelViewSet):
    queryset = Profile.objects.all()
    permission_classes = (IsOwnerOrStaffOrReadOnly,)

    def get_serializer_class(self):
        if self.action in ['list', 'create']:
            return BasicProfileSerializer
        elif get_object_or_404(self.queryset, pk = self.kwargs['pk']).owner == self.request.user or self.request.user.is_staff:
            return FullProfileSerializer

Is there a better / more correct way to do the lookup in the elif block?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.