我正在学习通用视图并创建一些Api。如何更新Model:“ Contacts”中的“ mobile”字段?
我想从url(mobile / update / user_id)获取用户ID。但是在创建查询集时,它不起作用。我想做这里提到的事情(#queryset = Contacts.objects.filter(id = Usertab.objects.filter(id = self.kwargs ['id'])。first()。contact.id))
'''python
class UpdateMobileAPIView(generics.UpdateAPIView):
queryset = Contacts.objects.filter(pk=Usertab.objects.all())
serializer_class = ContactsSerializer
lookup_field = 'pk'
def update(self,instance,request):
instance = self.get_object()
serializer= self.get_serializer(instance,data=request.data,partial=True)
if serializer.is_valid():
serializer.save()
return Response({"message":"mobile number updated successfully"})
else:
return Response({"message":"failed"})
''' 这些是模型
class Contacts(models.Model):
mobile = models.IntegerField(null=False)
Landline = models.IntegerField(null=False)
whats_app = models.IntegerField(null=False)
类Usertab(models.Model):
username = models.CharField(max_length=255,null=False,blank=False)
address = models.CharField(max_length=255,null=False,blank=False)
pin_code = models.CharField(max_length=255,null=False,blank=False)
contact = models.ForeignKey(Contacts,related_name="contacts_user")
类电子邮件(models.Model):
user = models.ForeignKey(Usertab,related_name="user_email")
email = models.CharField(max_length=255,null=False,blank=False)
is_verified = models.BooleanField(default=False)
'''
'''这是序列化器
class ContactsSerializer(ModelSerializer):
class Meta:
model = Contacts
fields = '__all__'
def update(self, instance, validated_data):
instance.mobile = validated_data.get('mobile', instance.mobile)
instance.save()
return instance
'''
TypeError:update()得到了意外的关键字参数'pk'
答案 0 :(得分:0)
我认为错误在于您的queryset
值。如果目标是
联系人模型,只需将查询集作为联系人模型中的所有项目即可。这样,查找字段可用于过滤整个数据集并编辑适当的条目。
class UpdateMobileAPIView(generics.UpdateAPIView):
queryset = Contacts.objects.all()
serializer_class = ContactsSerializer
lookup_field = 'pk'
def update(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response({"message": "mobile number updated successfully"})
else:
return Response({"message": "failed", "details": serializer.errors})