在部分模型更新期间手动传递其他数据

时间:2019-08-18 15:31:21

标签: django django-rest-framework

我必须根据请求的数据将用户传递到不同的字段。如果实例被“拒绝”,由于我使用rejected = True,因此我需要传递rejected_by = request.user和用户partial_update来手动更改这些值。我试图通过将其他数据传递到serializer_class来做到这一点,但这似乎不起作用。

class AcceptRejectCoreWord(generics.UpdateAPIView):
    queryset = WordCoreModel.objects.all()
    serializer_class = AcceptRejectCoreWordSerializer
    lookup_field = 'id'

    def patch(self, request, *args, **kwargs):
        user = get_user_model().objects.get(email=request.user)
        if not user.groups.filter(name="Moderator").exists():
            return Response({
                'error': 'Only moderators have permissions to view this endpoint'},
                status=status.HTTP_403_BAD_REQUEST)

        if request.data['rejected']:
            reject_reason = request.data['rejection_reason']
            if not reject_reason:
                return Response({
                    'error': 'Rejection reason is required'},
                    status=status.HTTP_400_BAD_REQUEST)
            self.serializer_class(accepted=False, accepted_dy=None, rejected=True, rejected_by=user, modified_by=user,
                                  publishing_status='rejected')
        if request.data['accepted']:
            self.serializer_class(rejected=False, rejected_by=None, accepted=True, accepted_dy=user, modified_by=user,
                                  publishing_status='published')

        return self.partial_update(request, *args, **kwargs)

我的序列化程序类包含此字段,但是在使用partial_update方法的情况下,我不知道如何更新它们。

class AcceptRejectCoreWordSerializer(serializers.ModelSerializer):
    part_of_speech_type = CoreWordSpeechPartDescriptionSerializer(
        many=True, required=False)

    class Meta:
        model = WordCoreModel
        fields = ['id', 'word_core', 'word_russian_typed',
                  'word_english_typed', 'part_of_speech_type', 'uncensored_word', 'modified_by', 'publishing_status',
                  'accepted', 'accepted_by', 'rejected', 'rejected_by', 'rejection_reason']
        extra_kwargs = {'id': {'read_only': False}}

    def update(self, instance, validated_data):
        word_descriptions = validated_data.pop('part_of_speech_type')
        core_word = WordCoreModel.objects.get(id=validated_data['id'])
        for word_description in word_descriptions:
            CoreWordSpeechPartDescription.objects.update(
                word=core_word, **word_description)
        return core_word

上面的实现给了我错误:TypeError: __init__() got an unexpected keyword argument 'accepted',它在以下一行上引发:self.serializer_class(accepted=False, accepted_dy=None, rejected=True, rejected_by=user, modified_by=user, publishing_status='rejected')

1 个答案:

答案 0 :(得分:0)

您应该使用this document来了解这些通用视图如何工作以及在哪里最好地自定义行为。如果查看update,您会看到它调用get_object(),然后使用返回的instance通过串行器执行部分更新。因此,最好只是将代码移到get_object()中,以使实例在使用data部分更新之前已经用您的字段进行了更新。