使用drf-nested-routers

时间:2018-05-19 17:25:32

标签: django django-rest-framework drf-nested-routers

我正在使用

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

我的 contacts / 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错误。

1 个答案:

答案 0 :(得分:1)

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

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