小编Kar*_*ūtė的帖子

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

我有一个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( …
Run Code Online (Sandbox Code Playgroud)

django rest django-rest-framework

7
推荐指数
1
解决办法
3157
查看次数

标签 统计

django ×1

django-rest-framework ×1

rest ×1