          serializer = self.get_serializer(instance, data=request.data, partial=partial)
          serializer.is_valid(raise_exception=True)
          self.perform_update(serializer)
  
          if getattr(instance, '_prefetched_objects_cache', None):
              # If 'prefetch_related' has been applied to a queryset, we need to
              # forcibly invalidate the prefetch cache on the instance.
              instance._prefetched_objects_cache = {}
  
          return Response(serializer.data)
 
</s> remove             # forcibly invalidate the prefetch cache on the instance.
 </s> add             # forcibly invalidate the prefetch cache on the instance,
            # and then re-prefetch related objects </s> remove         view = UserUpdate.as_view()
        pk = self.user.pk
        groups_pk = self.groups[0].pk
        request = factory.put('/', {'username': 'new', 'groups': [groups_pk]}, format='json')
        response = view(request, pk=pk)
        assert User.objects.get(pk=pk).groups.count() == 1
        expected = {
            'id': pk,
            'username': 'new',
            'groups': [1],
            'email': 'tom@example.com'
        }
        assert response.data == expected
 </s> add         self.groups.append(Group.objects.create(name='c'))
        request = factory.put(
            '/', {'username': 'new', 'groups': [group.pk for group in self.groups]}, format='json'
        )
        self.expected['username'] = 'new'
        self.expected['groups'] = [group.pk for group in self.groups]
        response = self.view(request, pk=self.user.pk)
        assert User.objects.get(pk=self.user.pk).groups.count() == 12
        assert response.data == self.expected
        # Update and fetch should get same result
        request = factory.get('/')
        response = self.view(request, pk=self.user.pk)
        assert response.data == self.expected
        queryset = self.filter_queryset(self.get_queryset())
        if queryset._prefetch_related_lookups:
          serializer = self.get_serializer(instance, data=request.data, partial=partial)
          serializer.is_valid(raise_exception=True)
          self.perform_update(serializer)
  
        queryset = self.filter_queryset(self.get_queryset())
        if queryset._prefetch_related_lookups:
              # If 'prefetch_related' has been applied to a queryset, we need to
              # forcibly invalidate the prefetch cache on the instance.
              instance._prefetched_objects_cache = {}
  
          return Response(serializer.data)
keep keep keep keep replace keep keep keep keep keep
 Re-prefetch related objects after updating (#8043)

* Re-prefetch related objects after updating

* Fix flake8 format

* Use _prefetch_related_lookups and refine test cases

* Add more test cases and refine prefetch checking 
rest_framework/mixins.py