使用嵌套路由非常简单:
定义您的文章模型 (models/article.py):
class Article(models.Model):
name = models.CharField(max_length=100, blank=False, null=False, default='')
...
定义您的评论模型 (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):
class ArticleAPIView(viewsets.ModelViewSet):
serializer_class = ArticleSerializer
....
定义您的评论视图 (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
您将获得以下文章的路线:
{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
最后,您将获得 cmets 的路线,例如:
{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