Cheng
Cheng

Reputation: 17894

Django REST Framework how to limit user access to certain serializer field

I have a model:

from django.db import models
from django.contrib.auth.models import Group

class Question(models.Model):
    text = models.TextField()
    group = models.OneToOneField(Group)

When being requested about questions, I only want to return the text part. Because users do not need to see the group part. However, when saving the model, I need to fill in the group part for the user.

Here is the serializer:

class QuestionSerializer(ModelSerializer):
    class Meta:
        model = Question
        fields = (text)

If I define the serializer like above, then I cannot do something like this when saving it:

def put(request, pk):
    data = JSONParser().parse(request)
    group = Group.objects.get(pk=pk)
    qSerializer = QuestionSerializer(data=data, group=group)  # the serializer does not know about group

So what should I in this case?


Update:

@Anush pointed me to the write direction, the solution is:

class QuestionSerializer(ModelSerializer):
    class Meta:
        model = Question
        fields = ('text','group')
        extra_kwargs = {'group': {'write_only': True}}

Then, in the view:

def put(...):
    data['group'] = group.pk
    serializer = QuestionSerializer(data=data)
    if serializer.is_valid():
        serializer.save()
    else:
        raise serializers.ValidationError(serializer.errors)

Upvotes: 1

Views: 664

Answers (1)

Anush Devendra
Anush Devendra

Reputation: 5475

you can make group write only in QuestionSerializer like:

class QuestionSerializer(ModelSerializer):
    class Meta:
        model = Question
        fields = ('text','group')
        extra_kwargs = {'group': {'write_only': True}}

learn more here

Upvotes: 2

Related Questions