如何使用Django REST Framework构建嵌套路由?

时间:2015-03-23 14:58:34

标签: python django rest django-rest-framework nested-resources

我想构建一个简单的API并选择Django REST Framework (DRF)。我希望以minimize path nesting Tom Christie(DRF的作者)向我指出。

有两种模式:文章评论 对于这些,我想构建以下API路径(使用 create [C] 读取[R] 更新[U] 访问):

/                      [R]
/articles/             [R]
/articles/:id/         [R]
/articles/:id/comments [R]
/comments/             [CRU]
/comments/:id          [R]

models.py:

class Article(models.Model):
    text = models.CharField(max_length=140, blank=False)
    recorded_at = models.DateTimeField(blank=False)
    modified_at = models.DateTimeField(auto_now_add=True)


class Comment(models.Model):
    message = models.CharField(max_length=140, blank=False)
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now_add=True)
    article = models.ForeignKey('Article', default=1, related_name='article')

serializers.py:

class ArticleSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Article


class CommentSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Comment

views.py:

class ArticleViewSet(mixins.RetrieveModelMixin,
                     mixins.ListModelMixin,
                     viewsets.GenericViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer


class CommentViewSet(mixins.CreateModelMixin,
                     mixins.RetrieveModelMixin,
                     mixins.ListModelMixin,
                     viewsets.GenericViewSet):
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer

urls.py:

router = DefaultRouter()
router.register(r'articles', ArticleViewSet)
router.register(r'comments', CommentViewSet)


urlpatterns = patterns('',
    url(r'^', include(router.urls)),
)

根级别的路径工作:

/                      [R]
/articles/             [R]
/articles/:id/         [R]
/comments/             [CRU]
/comments/:id          [R]

然而,嵌套路径返回404。

/articles/:id/comments [R]

1 个答案:

答案 0 :(得分:1)

您在ArticleViewSet ...

上需要这样的内容
@detail_route(methods=['get'])
def comments(self, request, pk=None):
    article = self.get_object()
    comments = article.comment_set.all()
    serializer = CommentSerializer(comments)
    return Response(serializer.data)