本文介绍了带有df-nested-router的Django-rest-framework嵌套URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 drf-nested-routers 包构建嵌套API.

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

但是/domains/1/nameservers/却提供了我拥有的所有名称服务器,不仅仅是一个与域#1相关的

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

我认为问题是我使用默认的教程NameServerViewSet实现

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.

以下是 drf-nested-routers github页面中的示例.

drf-nested-routers提供了嵌套的路由器,该路由器在下面生成url模式

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

\ domain {domain_pk} \ nameservers \<-来自的域的域名服务器

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

{domain_pk} \ domain {domain_pk} \ nameservers \ {pk} \<-来自{pk}的特定名称服务器,来自{domain_pk}的域

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

这里是一个例子:

# 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)),
)

推荐答案

解决方案来自作者艾伦.

以下是ViewSet的实现方式:

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)

这篇关于带有df-nested-router的Django-rest-framework嵌套URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 00:40