0

我有一個模型,我想爲它寫一個update()方法以便更新。 以下代碼段是我的模型:'collections.OrderedDict'object has no attribute'pk' - django rest framework

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方法,它返回以下錯誤:

AttributeError at /api/class/49/

'collections.OrderedDict' object has no attribute 'pk'

和錯誤發生在serializer.update(instance=klass, validated_data=serializer.data)一行。

+0

目前還不清楚你在這裏做什麼。你爲什麼要將序列化器的數據傳回自己? –

+1

你不應該顯式地調用'update()'。你應該調用'save()' –

+0

另外,你也不需要定義'update';另外,與表單一樣,如果傳遞顯式數據,initial_data將被忽略。這是各種各樣的錯誤。 –

回答

1

我不知道這是否有幫助。由於類似問題,我總是在序列化程序中添加'id'字段: id = serializers.ModelField(model_field = YourModel._meta.get_field('id'),required = False) 確保它是必需的= False,因爲何時你創建一個新的記錄'id'字段不存在。

相關問題