In the Django rest framework, is there a way to have multiple lookup fields? I know it doesn't sound very REST friendly.
I have a Company
model, and I want to list them through their country first, and then by a slug field, something like: /companies/<iso_country>/<slug>/
. Is there a way to do this?
Create mixin like:
class MultipleFieldLookupMixin(object):
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:
filter[field] = self.kwargs[field]
return get_object_or_404(queryset, **filter) # Lookup the object
and add this mixin to your viewset:
class YourCountryViewSet(MultipleFieldLookupMixin, generics.RetrieveAPIView):
lookup_fields = ('iso_country', 'slug')
...
source: http://www.django-rest-framework.org/api-guide/generic-views/#creating-custom-mixins
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With