Django REST Framework如何限制用户访问某些序列化程序字段

时间:2015-12-08 11:07:45

标签: django django-rest-framework

我有一个模特:

echo "Message from Admin"
cd /D G:\Tomcat_7\apache-tomcat-7.0.59\bin
call startup
start MicrosoftEdge.exe http://localhost:7211/LazyPeople

当被要求提问时,我只想返回from django.db import models from django.contrib.auth.models import Group class Question(models.Model): text = models.TextField() group = models.OneToOneField(Group) 部分。因为用户不需要查看text部分。但是,在保存模型时,我需要为用户填写group部分。

这是序列化器:

group

如果我像上面那样定义了序列化程序,那么在保存时我不能做这样的事情:

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

那么在这种情况下我该怎么办?

更新

@Anush向我指出了写方向,解决方法是:

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

然后,在视图中:

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