[英]ID parameter in Django REST API URL
我有兩個模型:
評論通過 ForeingKey 連接到文章。
我想創建一個端點,如:
{GET} /article/97/comments # get all comments of article (id:97)
{POST} /article/97/comments # create an comment for article (id=97)
但我想使用 GenericViewSet 或 ModelMixins。
你能指導我嗎,我該怎么做?
謝謝。
使用嵌套路由非常簡單:
定義您的文章 model ( models/article.py
):
class Article(models.Model):
name = models.CharField(max_length=100, blank=False, null=False, default='')
...
定義您的評論 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
):
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
最后,您將獲得以下評論的路線:
{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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.