代码之家  ›  专栏  ›  技术社区  ›  Anuj TBE

找不到带有DRF嵌套路由器的页面错误

  •  0
  • Anuj TBE  · 技术社区  · 7 年前

    我在用

    Django: 2.0  
    Djanfo REST Frameword: 3.8.2
    drf-nested-routers: 0.90.2
    

    我的 联系人/视图.py

    class ContactViewSet(viewsets.ModelViewSet):
        serializer_class = ContactSerializer
        permission_classes = (IsAuthenticated,)
    
        def get_queryset(self):
            return Contact.objects.filter(user=self.request.user)
    
    class ContactPhoneNumberViewSet(viewsets.ModelViewSet):
        serializer_class = ContactPhoneNumberSerializer
        permission_classes = (IsAuthenticated,)
    
        def get_queryset(self):
            print(self.kwargs)
            phone_numbers = ContactPhoneNumber.objects.all()
            return phone_numbers
    

    应用程序/urls.py

    from rest_framework_nested import routers
    
    from contacts.views import ContactViewSet, ContactPhoneNumberViewSet
    
    router = routers.SimpleRouter()
    router.register(r'contacts', ContactViewSet, 'contacts')
    contact_router = routers.NestedSimpleRouter(router, r'contacts', lookup='contact')
    contact_router.register(r'phone_number', ContactPhoneNumberViewSet, base_name='contact-phone-numbers')
    
    api_urlpatterns = [
        path('', include(router.urls)),
    ]
    
    urlpatterns = [
        path('api/', include(api_urlpatterns)),
        url(r'^admin/', admin.site.urls),
    ]
    

    使用此设置,我可以访问

    /api/contacts/           # <= list all contacts
    /api/contacts/<pk>/      # <= contact detail
    

    但在尝试进入

    /api/contacts/<pk>/phone_number/           # <= list all phone numbers
    

    它正在给予 Page Not Found 错误。

    我也试过传球 <phone_number_pk> 但是仍然 Page not Found 收到错误。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Sumeet Kumar    7 年前
    api_urlpatterns = [
        path('', include(router.urls)),
        path('', include(contact_router.urls)),
    ]
    

    您还需要单独注册嵌套的URL。