'collections.OrderedDict' object has no attribute 'pk' - django rest framework

北战南征 提交于 2021-02-07 19:10:37

问题


I have a model and I want to write an update() method for it in order to update. The below snippet is my model:

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)

and the below snippet is corresponding 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

And for update, I use below snippet:

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)

but when I send data with PUT method, it returns below error:

AttributeError at /api/class/49/

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

and the error occurs in serializer.update(instance=klass, validated_data=serializer.data) line.


回答1:


Just run on the same error. In my case the problem was I accesessed serializer.data before doing serializer.save(). Google dropped me here, so maybe someone else will also find this helpful.

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




回答2:


Will in my case I was doing,

champions_list = []

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

and the correct one

champions_list = []

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

and make sure that you return the id inside the field of the serializer




回答3:


i don't know if this helps. I always add the id field in the serializer due to that similar issue:

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

Make sure it's required=False because when you create a new record the id field is not present.



来源:https://stackoverflow.com/questions/46805662/collections-ordereddict-object-has-no-attribute-pk-django-rest-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!