From 16e7148d3b527ce3a6a63d509ed7dec6d1f65417 Mon Sep 17 00:00:00 2001 From: Ragheed Al-midani Date: Fri, 25 Sep 2015 05:00:58 -0400 Subject: [PATCH] Memoize object lookups in GenericApiView --- rest_framework/generics.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/rest_framework/generics.py b/rest_framework/generics.py index 88438e8c4..0324fcb4d 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -75,12 +75,19 @@ class GenericAPIView(views.APIView): def get_object(self): """ - Returns the object the view is displaying. + Returns the object the view is displaying. The value is memoized across + the lifecycle of the view to reduce database hits when e.g. delegating + from custom actions in a ModelViewSet to built-in actions. You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf. """ + # Check if obj has been looked up (and therefore memoized) before. + obj = getattr(self, 'obj', None) + if obj is not None: + return obj + queryset = self.filter_queryset(self.get_queryset()) # Perform the lookup filtering. @@ -99,6 +106,9 @@ class GenericAPIView(views.APIView): # May raise a permission denied self.check_object_permissions(self.request, obj) + # Memoize obj for potential lookups in the future. + self.obj = obj + return obj def get_serializer(self, *args, **kwargs):