Skip to content

Instantly share code, notes, and snippets.

@nik-hil
Last active May 7, 2024 10:47
Show Gist options
  • Save nik-hil/9a7863536857d32e4b5a to your computer and use it in GitHub Desktop.
Save nik-hil/9a7863536857d32e4b5a to your computer and use it in GitHub Desktop.
Django REST framework support only one lookup field at a time. To support more than one field we have to use MultipleFieldLookupMixin. But it has a limitation. It require all fields to be present in URL. I have different requirement. I can call view using two differnet identifier.
class MultipleFieldLookupORMixin(object):
"""
Actual code http://www.django-rest-framework.org/api-guide/generic-views/#creating-custom-mixins
Apply this mixin to any view or viewset to get multiple field filtering
based on a `lookup_fields` attribute, instead of the default single field filtering.
"""
def get_object(self):
queryset = self.get_queryset() # Get the base queryset
queryset = self.filter_queryset(queryset) # Apply any filter backends
filter = {}
for field in self.lookup_fields:
try: # Get the result with one or more fields.
filter[field] = self.kwargs[field]
except Exception:
pass
return get_object_or_404(queryset, **filter) # Lookup the object
class RetrieveUserView(MultipleFieldLookupORMixin, generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
lookup_fields = ('account', 'username')
@j-millan
Copy link

j-millan commented Aug 8, 2021

Very useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment