Search code examples
djangodjango-rest-frameworkdrf-nested-routers

Django-rest-framework nested urls with drf-nested-routers


I am building nested API with drf-nested-routers package.

However /domains/1/nameservers/ gives me all nameservers I have, not only one related to domain#1

I think the problem is that I use default tutorial NameServerViewSet implementation

class NameserverViewSet(viewsets.ModelViewSet):
    queryset = Nameserver.objects.all()
    serializer_class = NameserverSerializer

Please help me code it right way.

Below are examples from drf-nested-routers github page.

drf-nested-routers provides nested router that generates url patterns below

\domain\ <- Domains list \domain{pk}\ <- One domain, from {pk]

\domain{domain_pk}\nameservers\ <- Nameservers of domain from

{domain_pk} \domain{domain_pk}\nameservers\ {pk}\ <- Specific nameserver from {pk}, of domain from {domain_pk}

Here is an example:

# urls.py
from rest_framework_nested import routers
from views import DomainViewSet, NameserverViewSet
(...)

router = routers.SimpleRouter()
router.register(r'domains', DomainViewSet)

domains_router = routers.NestedSimpleRouter(router, r'domains', lookup='domain')
domains_router.register(r'nameservers', NameserverViewSet)

urlpatterns = patterns('',
    url(r'^', include(router.urls)),
    url(r'^', include(domains_router.urls)),
)

Solution

  • Solution came from Alan, the author.

    Here is how ViewSet should be implemented:

    class NameserverViewSet(viewsets.ViewSet):
        queryset = Nameserver.objects.all()
    
        def list(self, request, domain_pk=None):
            queryset = self.queryset.filter(domain=domain_pk)
            serializer = NameserverSerializer(queryset, many=True)
            return Response(serializer.data)
    
        def retrieve(self, request, pk=None, domain_pk=None):
            queryset = self.queryset.get(pk=pk, domain=domain_pk)
            serializer = NameserverSerializer(queryset)
            return Response(serializer.data)