在请求后为序列化器指定django-rest-framework字段?

时间:2019-01-13 21:49:03

标签: django django-rest-framework

我有以下代码:

models.py

class Interview(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, help_text="The Primary Key of the Interview")
    organization = models.ForeignKey(Organization, on_delete=models.CASCADE, help_text="The Primary Key of the Organization in the interview")
    question = name = models.CharField(max_length=200, help_text="The Question")

serializers.py

class InterviewSerializer(serializers.ModelSerializer):
    class Meta:
        model = Interview
        fields = ('organization', 'question')

views.py

class InterviewViewset(viewsets.ModelViewSet):
    """
    API endpoint that allows Interviews to be viewed or edited.
    """
    serializer_class = InterviewSerializer

现在,创建采访的请求主体需要以下字段:

{
  "organization": "string",
  "question": "string"
}

我希望将采访对象的组织自动设置为当前的用户组织(request.user.Organization-我有一个自定义的用户模型)。如何为我的视点做优雅的设计?

1 个答案:

答案 0 :(得分:0)

一种方法(可能是最好的方法)是重写ModelSerializer类的save / create / update方法。 DRF docs about it

您可以在其中使用self.context.get("request")来获取当前用户。而且,如果您仍然需要organization字段进行序列化,只需将其设为read_only=True