Created
February 27, 2021 22:44
-
-
Save ronaldgrn/9592edd61b37010fda46f6ae5d2a4a1a to your computer and use it in GitHub Desktop.
drf viewset multiple field lookup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MultiLookupModelViewSet(ModelViewSet): | |
""" | |
Allows you to perform lookups on one or more fields | |
""" | |
lookup_fields = ["pk"] # Override with your lookup fields | |
def get_object(self): | |
""" | |
Returns the object the view is displaying. | |
""" | |
queryset = self.filter_queryset(self.get_queryset()) | |
for lookup_url_kwarg in self.lookup_fields: | |
assert lookup_url_kwarg in self.kwargs, ( | |
"Expected view %s to be called with a URL keyword argument " | |
'named "%s". Fix your URL conf, or set the `.lookup_fields` ' | |
"attribute on the view correctly." % (self.__class__.__name__, lookup_url_kwarg) | |
) | |
filter_kwargs = {field: self.kwargs[field] for field in self.lookup_fields} | |
obj = get_object_or_404(queryset, **filter_kwargs) | |
# May raise a permission denied | |
self.check_object_permissions(self.request, obj) | |
return obj |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment