Home > Software design >  How to update self.request.user field in django rest framework?
How to update self.request.user field in django rest framework?

Time:09-30

I need to update the requested user field when I create the organization from OrganizationViewSet as below,

class OrganizationViewSet(viewsets.ModelViewSet):
    queryset = Organization.objects.all()
    serializer_class = OrganizationSerializer
    permission_classes = [permissions.IsAuthenticated]

   def perform_create(self, serializer):
        serializer.save(admin_user=self.request.user)
        data = serializer.data
        org_id = data['id']
        self.request.user.update(organization=org_id) # Error is coming from this line

The above code generates the following error,

'User' object has no attribute 'update'

Here is my User models.py file

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    organization = models.ForeignKey(
        "organization.Organization", on_delete=models.CASCADE, null=True, blank=True)
    first_name = models.CharField(max_length=200, blank=True)
    last_name = models.CharField(max_length=200, blank=True)
    phone = models.CharField(max_length=20, blank=True)

So my question is, how can I update the requested user organization? Any help?

CodePudding user response:

update is a method on the QuerySet and not on a Model

You can do model.save as follows to have the desired behavior

self.request.user.organization = org_id
self.request.user.save()
  • Related