Django REST框架 - 取决于http方法的相同URL的不同视图

Kar*_*ūtė 7 django rest django-rest-framework

我有一个REST框架API,我必须根据一个方法将URL分配给两个不同的视图.

架构是这样的:

bookshop/authors/ - lists all authors, with POST - adds an author

bookshop/authors/<author>/ - with GET - gets details for an author, including books

bookshop/authors/<author>/ - with POST - creates a posting of a book for the same author. 

bookshop/authors/<author>/<book>/ - gets a book, no posting
Run Code Online (Sandbox Code Playgroud)

通常,对于我的所有API,我使用Viewsets with Routers.

我试过这样做:

urlpatterns = patterns(
    '',
    url(r'^author/(?P<author>[0-9]+)',
        AuthorViewSet.as_view({'get': 'retrieve'}),
        name='author-detail'),
    url(r'^author/(?P<author>[0-9]+)',
        BookViewSet.as_view({'post': 'create'})),
)
Run Code Online (Sandbox Code Playgroud)

但随后它转到第一个URL并且视图集检查方法并抛出异常MethodNotAllowed.

我试着像这样抓住它:

try: 
    urlpatterns = patterns( 
    '', 
    url(r'^author/(?P<author>[0-9]+)',  
    AuthorViewSet.as_view({'get': 'retrieve'}), 
    name='author-detail') 
    ) 
except MethodNotAllowed: 
    urlpatterns = patterns( 
    '', 
    url(r'^author/(?P<author>[0-9]+)', 
    BookViewSet.as_view({'post': 'create'})), 
    )
Run Code Online (Sandbox Code Playgroud)

但它也不起作用.

有没有办法使用viewsets?

Rex*_*ury 0

使用 时Viewsets,通常您需要向路由器注册视图,而不是像您所做的那样直接绑定视图。路由器将负责将请求“路由”到正确的处理程序。

查看:

http://www.django-rest-framework.org/api-guide/viewsets/#example

http://www.django-rest-framework.org/api-guide/routers/