Last active
May 7, 2024 10:47
-
-
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.
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 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') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very useful.