Update field OneToOneField - Djando rest framework

1

I have a model called worker

class Worker(models.Model):
    name = models.CharField(max_length=300)
    code = models.CharField(max_length=100)
    user = models.OneToOneField(User, null=True, blank=True)

    def __str__(self):
        return self.name

Which has a 1 to 1 relationship with the user model of django This is my serializer:

class WorkerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Worker
        fields = '__all__'

and This my viewset:

@transaction.atomic
    def update(self, request, *args, **kwargs):
        with transaction.atomic():
            try:
                instance = self.get_object()
                instance.id = kwargs.get('pk')
                serializer = WorkerSerializer(instance=instance, data=request.data)
                if serializer.is_valid(raise_exception=True):
                    self.perform_update(serializer)
                    return Response({"status": True, "results": "Datos actualizados correctamente"},
                                    status=status.HTTP_201_CREATED)
            except ValidationError as err:
                return Response({"status": False, "error_description": err.detail}, status=status.HTTP_400_BAD_REQUEST)

The problem I have is that when wanting to update the user field, it asks for the id of the user but I want to update it by putting in the client its username how can I do this? and how do I verify if that worker already has an associated user ?

    
asked by Piero Pajares 14.04.2018 в 18:40
source

2 answers

1

I answer first how to verify if a worker already has a user.

Being an update with the self.get_object() you get the object directly so if doing a if instance.user != None: you should check if that field is not empty and treat it the way you want.

I answer the second question.

If what you want is to pass the name of your user as a parameter, you can make the following modification:

@transaction.atomic
def update(self, request, *args, **kwargs, nombre):
    with transaction.atomic():
        try:
            instance = User.objects.get(username = nombre)
            serializer = WorkerSerializer(instance=instance, data=request.data)
            if serializer.is_valid(raise_exception=True):
                self.perform_update(serializer)
                return Response({"status": True, "results": "Datos actualizados correctamente"},
                                status=status.HTTP_201_CREATED)
        except ValidationError as err:
            return Response({"status": False, "error_description": err.detail}, status=status.HTTP_400_BAD_REQUEST)

I would recommend working with slugs if you want to work with the names. Although for that you will have to make changes in the User model, in your serializer and in your viewsets.

    
answered by 16.04.2018 / 10:33
source
1

You could use something like this:

obj = Worker.objects.get(pk=10)
obj.name = "nameNew"
obj.code = "codeNew"
obj.nameUser = "userName" #from model User
obj.user.save()#save model User

I hope you'll be lucky

    
answered by 17.04.2018 в 23:49