2017-07-18 60 views
0

休息框架有一個問題: 建立與視圖和路由器的API。ViewSet和路由器在休息框架

我想通過API URL序列化用戶帖子這樣的: /API /用戶/ 用戶ID /職位/ , 但路由器不能老是坐不住了。 這表明我的正則表達式的模式:(?P [A-Z0-9] +)?

^API/^ ^用戶/職位/ $ [名稱= '用戶帖子']

class UserViewSet(viewsets.ReadOnlyModelViewSet): 
    queryset = User.objects.all() 
    serializer_class = UserSerializer 

    @list_route() 
    def posts(self, page): 
     user = self.get_object() 
     post_set = Post.objects.filter(owner=user) 
     paginator = Paginator(post_set, 16) 
     serializer = PostSerializer(paginator.page(page), many=True) 
     return Response(serializer.data) 

有任何想法如何正確地強制這項工作?提前致謝!

+0

它看起來像你錯過了在'/''後posts'你的網址 –

+0

哦,也許我應該試試@detail_route – Michael

+0

我的意思是在這裏:'^ users/posts。(?P [a-z0-9] +)/?$'我認爲應該是這樣的:'^ users/posts /(?P [a-z0-9] +) /?$' –

回答

0

觀點:

@detail_route() 
def posts(self, request, pk, page): 
    user = self.get_object() 
    post_set = Post.objects.filter(owner=user) 
    paginator = Paginator(post_set, 16) 
    serializer = PostSerializer(paginator.page(page), many=True, context={'request': request}) 
    return Response(serializer.data) 

網址:

router = DefaultRouter() 
router.register(r'posts', views.PostViewSet) 
router.register(r'users', views.UserViewSet) 
user_posts = views.UserViewSet.as_view({ 
    'get': 'posts' 
}) 

urlpatterns = [ 
    url(r'^', include(router.urls)), 
    url(r'^users/(?P<pk>\w+)/posts/(?P<page>[0-9]+)', user_posts), 
] 
0
class UserViewSet(viewsets.ReadOnlyModelViewSet): 
    queryset = User.objects.all() 
    serializer_class = UserSerializer 

    @detail_route() 
    def posts(self, request, pk): 
     user = self.get_object() 
     post_set = Post.objects.filter(owner=user) 
     paginator = Paginator(post_set, 16) 
     page= request.query_params.get('page', 1) 
     serializer = PostSerializer(paginator.page(page), many=True, context={'request': request}) 
     return Response(serializer.data) 

urls.py

router.register('user', UserViewSet)