gpt4 book ai didi

python - 'collections.OrderedDict' 对象没有属性 'pk' - django rest 框架

转载 作者:行者123 更新时间:2023-12-03 18:19:13 25 4
gpt4 key购买 nike

我有一个模型,我想写一个 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 发送数据时方法,它返回以下错误:

AttributeError at /api/class/49/

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


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

最佳答案

刚刚遇到了同样的错误。
就我而言,问题是我访问了 serializer.data做之前serializer.save() .
谷歌把我放在这里,所以也许其他人也会觉得这很有帮助。
来源:https://github.com/encode/django-rest-framework/issues/2964

关于python - 'collections.OrderedDict' 对象没有属性 'pk' - django rest 框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46805662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com