Search code examples
djangopython-3.xdjango-rest-frameworkdjango-serializerdjango-generic-views

How to update a single field in a model using UpdateAPIView from Djangorestframework?


I'm learning generic views and creating some APIs. How can I update the field: mobile from Model:Contacts?

I want to get the user id from URL (mobile/update/user_id) But while creating the queryset it's not working. I want to do something like the one mentioned here:

#queryset = Contacts.objects.filter(id=Usertab.objects.filter(id=self.kwargs['id']).first().contact.id))
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"})

These are models

class Contacts(models.Model):

    mobile = models.IntegerField(null=False)
    Landline = models.IntegerField(null=False)
    whats_app = models.IntegerField(null=False)


class 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")


class Email(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)

This is the serializer

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() got an unexpected keyword argument 'pk'

Solution

  • I figure the error is with your queryset value. if the target is a field in the Contacts model, simply have the queryset as all items in the Contacts model. This way the lookup field can be a used to filter the entire dataset and edit the appropriate entry.

    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})