Skip to content

Instantly share code, notes, and snippets.

@ronaldgrn
Created February 27, 2021 22:44
Show Gist options
  • Save ronaldgrn/9592edd61b37010fda46f6ae5d2a4a1a to your computer and use it in GitHub Desktop.
Save ronaldgrn/9592edd61b37010fda46f6ae5d2a4a1a to your computer and use it in GitHub Desktop.
drf viewset multiple field lookup
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