0

我在用着

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

我的联系人/views.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

app/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收到错误。

4

1 回答 1

2
api_urlpatterns = [
    path('', include(router.urls)),
    path('', include(contact_router.urls)),
]

您还需要单独注册嵌套网址

于 2018-05-19T19:20:26.920 回答