1

我有一个ListCreateAPIView,我想用默认值填充一个字段,以防 request.DATA 未提供。

问题是:我应该在哪里做?

我无法修改它,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',
        )
4

1 回答 1

0

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

于 2013-09-05T19:38:26.873 回答