Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix UpdateModelMixin to work when no queryset is defined is defined on the view #9314

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions rest_framework/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,14 @@ def update(self, request, *args, **kwargs):
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)

queryset = self.filter_queryset(self.get_queryset())
if queryset._prefetch_related_lookups:
if hasattr(instance, '_prefetched_objects_cache'):
Comment on lines -73 to +72
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When only get_object is defined, I assume that folks are unlikely to have advanced prefetches in their method (although it's very much possible).

If some things were prefetched, we assume that there is a get_queryset method.

# If 'prefetch_related' has been applied to a queryset, we need to
# forcibly invalidate the prefetch cache on the instance,
# and then re-prefetch related objects
# forcibly invalidate the prefetch cache on the instance
instance._prefetched_objects_cache = {}
prefetch_related_objects([instance], *queryset._prefetch_related_lookups)
queryset = self.filter_queryset(self.get_queryset())
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is still expecting get_queryset or queryset to be defined and will raise an AssertError if it is not, which means it will still not be backwards compatabile with 3.14 correct?

Copy link
Contributor

@yuekui yuekui Mar 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How is it possible that self has '_prefetched_objects_cache' defined without defining queryset or get_queryset?

Copy link
Contributor Author

@browniebroke browniebroke Mar 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's what I meant by my comment earlier, one might do:

class UserRetrieveWithoutQuerySet(generics.RetrieveUpdateAPIView):
    serializer_class = UserSerializer

    def get_object(self):
        return User.objects.prefetch_related('groups').get(pk=self.kwargs['pk'])

In such case, I would argue that it's reasonable to require users to override the get_queryset method... The error message says exactly that. Would probably need to be documented better, though.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably just an extra if statement or try catch would solve all these cases.

if getattr(queryset, '_prefetch_related_lookups', None):
# And then re-prefetch related objects
prefetch_related_objects([instance], *queryset._prefetch_related_lookups)

return Response(serializer.data)

Expand Down
15 changes: 15 additions & 0 deletions tests/test_prefetch_related.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ class UserUpdateWithoutPrefetchRelated(generics.UpdateAPIView):
serializer_class = UserSerializer


class UserRetrieveWithoutQuerySet(generics.RetrieveUpdateAPIView):
serializer_class = UserSerializer

def get_object(self):
return User.objects.get(pk=self.kwargs['pk'])


class TestPrefetchRelatedUpdates(TestCase):
def setUp(self):
self.user = User.objects.create(username='tom', email='tom@example.com')
Expand Down Expand Up @@ -90,3 +97,11 @@ def test_db_query_count(self):
)
with self.assertNumQueries(16):
UserUpdateWithoutPrefetchRelated.as_view()(request, pk=self.user.pk)

def test_can_update_without_queryset(self):
request = factory.patch('/', {'username': 'new'})
response = UserRetrieveWithoutQuerySet.as_view()(request, pk=self.user.pk)
assert response.data['id'] == self.user.id
assert response.data['username'] == 'new'
self.user.refresh_from_db()
assert self.user.username == 'new'
Loading