休息框架有问题: 使用视图和路由器构建api。
我希望api按照以下方式将用户的帖子序列化: / api / users / 用户ID / posts / 页面, 但路由器不能忍受它。 它建议我使用regexp模式:
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s : %(message)s')
logging.getLogger("requests").setLevel(logging.WARNING)
logging.getLogger("urllib3").setLevel(logging.WARNING)
^api/ ^ ^users/posts\.(?P<format>[a-z0-9]+)/?$ [name='user-posts']
有任何想法如何正确地推动这项工作?提前谢谢!
答案 0 :(得分:1)
的观点:
@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),
]
答案 1 :(得分: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)