Django REST API URL 中的 ID 参数

Django REST API URL 中的 ID 参数

问题描述:

我有两个模型:

  1. 文章
  2. 评论

评论通过 ForeingKey 连接到文章.

Comments are connected to Article with ForeingKey.

我想创建一个端点,如:

I want to create an endpoint like:

       {GET} /article/97/comments  # get all comments of article (id:97)
       {POST} /article/97/comments  # create an comment for article (id=97)

但我想使用 GenericViewSet 或 ModelMixins.

But I want to use GenericViewSet or ModelMixins.

你能指导我吗,我该怎么做?

Can you guide me, how can I do so?

谢谢.

使用嵌套路由非常简单:

It's very simple using nested routes:

定义您的文章模型 (models/article.py):

Define your Article model (models/article.py):

class Article(models.Model):
    name = models.CharField(max_length=100, blank=False, null=False, default='')
    ...

定义您的评论模型 (models/comment.py):

Define your Comment model (models/comment.py):

class Comment(models.Model):
    content = models.CharField(max_length=100, blank=False, null=False, default='')
    article = models.ForeignKey(Article, related_name='comments', on_delete=models.CASCADE, blank=True, null=True)
    ...

定义您的文章视图 (views/article.py):

Define your Article view (views/article.py):

class ArticleAPIView(viewsets.ModelViewSet):
    serializer_class = ArticleSerializer
    ....

定义您的评论视图 (views/comment.py):

Define your Comment view (views/comment.py):

class CommentAPIView(viewsets.ModelViewSet):
    serializer_class = CommentSerializer
    ...

定义你的路由(urls.py):

from django.urls import path
from app.domain.api import views
from rest_framework_extensions.routers import ExtendedSimpleRouter

urlpatterns: list = []

router: ExtendedSimpleRouter = ExtendedSimpleRouter()
articles_router = router.register('articles', views.ArticleAPIView, basename='articles')
articles_router.register(
    'comments',
    views.CommentAPIView,
    basename='comments',
    parents_query_lookups=['article']
)
urlpatterns += router.urls

您将获得以下文章的路线:

You will get routes for articles like:

{GET} /articles/          -> Get list
{GET} /articles/{id}/     -> Get by id
{POST} /articles/         -> Create
{PUT} /articles/{id}/     -> Update
{PATCH} /articles/{id}/   -> Partial update
{DELETE} /articles/{id}/  -> Delete

最后,您将获得以下评论的路线:

Finally, you will get routes for comments like:

{GET} /articles/{parent_lookup_article}/comments/          -> Get list
{GET} /articles/{parent_lookup_article}/comments/{id}/     -> Get by id
{POST} /articles/{parent_lookup_article}/comments/         -> Create
{PUT} /articles/{parent_lookup_article}/comments/{id}/     -> Update
{PATCH} /articles/{parent_lookup_article}/comments/{id}/   -> Partial update
{DELETE} /articles/{parent_lookup_article}/comments/{id}/  -> Delete