gpt4 book ai didi

Django-rest-framework 嵌套 url 与 drf-nested-routers

转载 作者:行者123 更新时间:2023-12-02 09:41:32 24 4
gpt4 key购买 nike

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

但是 /domains/1/nameservers/ 为我提供了我拥有的所有域名服务器,而不仅仅是与domain#1相关的域名服务器

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

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

请帮我正确编码。

以下是来自 drf-nested-routers github page 的示例.

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

\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}

这是一个例子:

# 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来自Alan , 作者。

以下是 ViewSet 的实现方式:

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)

关于Django-rest-framework 嵌套 url 与 drf-nested-routers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22194499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com