Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rest calls with multiple lookup fields for reverse lookup

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?

like image 247
marcaurele Avatar asked Jan 26 '14 16:01

marcaurele


1 Answers

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

like image 131
Bulgantamir Avatar answered Oct 21 '22 12:10

Bulgantamir