我有一个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)