4

我有一个模型,我想update()为它写一个方法来更新。下面的代码片段是我的模型:

class Klass(models.Model):
    title = models.CharField(max_length=50)
    description = models.CharField(max_length=500)
    university = models.CharField(max_length=50,blank=True, null=True)
    teacher = models.ForeignKey(Profile, related_name='teacher', on_delete=models.CASCADE)

下面的代码片段是对应的Serializer

class KlassSerializer(ModelSerializer):
        teacher = ProfileSerializer()
        url = HyperlinkedIdentityField(view_name='mainp-api:detail', lookup_field='pk')
        klass_settings = KlassSettingsSerializer()

    class Meta:
        model = Klass
        fields = ('url', 'id', 'title', 'description', 'university','teacher')

    
    def update(self, instance, validated_data):
        instance.title = validated_data.get('title', instance.title)
        instance.description = validated_data.get('description', instance.description)
        instance.university = validated_data.get('university', instance.university)
        instance.save()

        return instance

对于更新,我使用以下代码段:

class KlassAPIView(APIView):    
    def put(self, request, pk=None):
        if pk == None:
            return Response({'message': 'You must specify class ID'}, status=HTTP_400_BAD_REQUEST)

        klass = Klass.objects.get(pk=pk)
        if request.user.profile.type != 't':
            raise PermissionDenied(detail={'message': 'You aren't teacher of this class, so you can't edit information.'})

        serializer = KlassSerializer(data=request.data, context={'request': request})
        serializer.initial_data['teacher'] = request.user.profile.__dict__

        if serializer.is_valid():
            serializer.update(instance=klass, validated_data=serializer.data)  # Retrieve teacher and store
            return Response({'data': serializer.data}, status=HTTP_200_OK)
        else:
            return Response({'data': serializer.errors}, status=HTTP_400_BAD_REQUEST)

但是当我用方法发送数据时PUT,它返回以下错误:

/api/class/49/ 处的 AttributeError

'collections.OrderedDict' 对象没有属性 'pk'

并且错误发生在serializer.update(instance=klass, validated_data=serializer.data)一行中。

4

4 回答 4

15

刚刚遇到同样的错误。

就我而言,问题是我serializer.data在做serializer.save().

谷歌把我丢在这里,所以也许其他人也会觉得这很有帮助。

来源:https ://github.com/encode/django-rest-framework/issues/2964

于 2019-03-14T23:21:39.037 回答
2

我不知道这是否有帮助。id由于类似的问题,我总是在序列化程序中添加该字段:

id = serializers.ModelField(model_field=YourModel._meta.get_field('id'), required=False)

确保这是required=False因为当您创建新记录时该id字段不存在。

于 2018-01-10T19:27:58.570 回答
2

就我而言,我正在做:

champions_list = []

for champion in champions_serializer.data:
   c = {"id": champion.id}
   champions_list.append(c)

正确的做法是:

champions_list = []

for champion in champions_serializer.data:
   c = {"id": champion["id"]}
   champions_list.append(c)

并确保在序列化程序中返回 id。

于 2020-05-03T08:26:59.667 回答
0

此问题的许多答案说明serializer.save()必须在使用之前调用serializer.data

就我而言,我肯定是在调用serializer.save(),但是,我在我的序列化程序上覆盖了该save方法,并且没有self.instance在该方法中设置序列化程序。

因此,如果您要覆盖save,请务必执行以下操作:

class MySerializer(serializers.ModelSerializer):
    def save(self, *args, **kwargs):
        ...
        self.instance = instance
        return self.instance
于 2021-05-03T05:33:27.963 回答