在CreateAPIView中添加默认值的位置?

时间:2013-09-05 16:48:54

标签: django-rest-framework

我有一个ListCreateAPIView,如果请求没有提供,我想在其中使用默认值填充字段。

问题是:我应该在哪里做到这一点?

我无法修改request.DATA,因为它是不可变的,我不想复制/粘贴CreateMixin实现。

这是我的代码:

class ObjectiveList(generics.ListCreateAPIView):
    model = Objective
    serializer_class = ObjectiveSerializer
    permission_classes = (permissions.IsAuthenticated,)

    def create(self, request, *args, **kwargs):

        # provide a default value
        objective_definition_id = request.DATA.get('objective_definition',-1)
        data = request.DATA.copy()
        if objective_definition_id == -1:
            # support for 0.9.1 version of iOS and below
            logger.info(str(self.request.DATA))
            mission_url = request.DATA["mission"]
            objectivedefinition_pk = self.default_objectivedefinition_id(mission_url)
            data["objective_definition"]=objectivedefinition_pk

        # I would want to do something like this but I can't
        # request.DATA = data
        # super(ObjectiveList,self).create(request, *args, **kwargs)

        # copy/paste of the super class implementation
        serializer = self.get_serializer(data=data, files=request.FILES)

        if serializer.is_valid():
            self.pre_save(serializer.object)
            self.object = serializer.save(force_insert=True)
            self.post_save(self.object, created=True)
            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data, status=status.HTTP_201_CREATED,
                    headers=headers)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

这是我的序列化器:

class ObjectiveSerializer(serializers.HyperlinkedModelSerializer):
    objective_definition = serializers.PrimaryKeyRelatedField(many=False, read_only=False, required=False, default=toto)

    class Meta:
        model = Objective
        fields = (
            'url',
            'objective_definition',
        )

1 个答案:

答案 0 :(得分:0)

您可以在该字段中使用default=参数,但不知道这是否符合您的使用案例?