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 django's user model. 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 I want to update the user field, it asks me for the user's id, but I want to update by putting their username in the client, how can I do this? And how do I check if that worker already has an associated user ?
I answer first how to check if a worker already has a user.
Being an update with
self.get_object()
it you get the object directly so if you do an itif instance.user != None:
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:
I would recommend working with slugs if you want to work with names. Although for that you will have to make modifications in the User model, in your serializer and in your viewsets.
You could use something like this:
I hope it works for you, good luck