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

时间:2016-05-05 15:46:27

标签: django rest django-rest-framework

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

架构是这样的:

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

一般情况下,对于我的所有API,我都使用带有路由器的Viewsets。

我试过这样做:

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'})),
)

然后它转到第一个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'})), 
    )

但它也不起作用。

有没有办法使用viewsets?

2 个答案:

答案 0 :(得分:2)

问题是以这种方式组织API会破坏RESTful约定。打破RESTful约定并不总是坏事,但通常代表一种糟糕的设计,当然也意味着使用围绕restframework设计的第三方软件来支持您的架构更加困难。所以我的建议是将您的API架构更新为:

GET  bookshop/authors/ - lists all authors
POST bookshop/authors/ - creates an author
GET  bookshop/authors/<author>/ - gets details for an author
POST bookshop/authors/<author>/books/ - creates a book for an author
GET  bookshop/authors/<author>/books/<book> - gets a book

如果你需要添加帖子,你也可以(我不确定对象之间的关系,所以不确定下面是否准确地表示了这种关系)。

POST bookshop/authors/<author>/books/<book>/postings - creates a posting
GET  bookshop/authors/<author>/books/<book>/postings/<posting> - gets a posting

答案 1 :(得分:0)

使用Viewsets时,通常您会想要使用路由器注册视图,而不是像您一样直接绑定视图。路由器将负责&#34;路由&#34;对正确处理程序的请求。

结帐:

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

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