I have a REST framework API and I have to dispatch an url to 2 different views, depending on a method.
the architecture is like this:
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
In general, for all my API I'm using Viewsets with Routers.
I tried doing this:
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'})),
)
but then it goes to the first url and the viewset checks for methods and throws an exception MethodNotAllowed.
I tried to catch it like this:
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'})),
)
But it doesn't work too.
Is there any way to do it using viewsets?
bookshop/authors/<author>/ - with POSTthat in particular.. Why not change that to a put or a patchPOSTtoauthors/Lindgren/the first view with that url will always be matched first. In the example aboveAuthorViewSetwill be used for bothPOSTandGET.BookViewSetwill never be used. BecauseAuthorViewSetis matched first since it shares the same url withBookViewSetandBookViewSetcomes after it