You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用指定DRF视图为同一URL配置不同HTTP方法对应逻辑

Django REST Framework 指定视图类的路由配置实现

1. 视图类定义

完全使用你指定的基础视图类实现,不使用组合视图或ViewSet:

作者列表与创建相关视图

from rest_framework.generics import ListAPIView, CreateAPIView, RetrieveAPIView
from .models import Author, Book
from .serializers import (
    AuthorListSerializer,
    AuthorCreateSerializer,
    AuthorDetailSerializer,
    BookCreateSerializer,
    BookListSerializer
)

# 处理GET /bookshop/authors/:列出所有作者
class AuthorListView(ListAPIView):
    queryset = Author.objects.all()
    serializer_class = AuthorListSerializer

# 处理POST /bookshop/authors/:添加作者
class AuthorCreateView(CreateAPIView):
    queryset = Author.objects.all()
    serializer_class = AuthorCreateSerializer

作者详情与关联书籍创建视图

# 处理GET /bookshop/authors/<author_id>/:获取作者详情(含书籍)
class AuthorDetailView(RetrieveAPIView):
    queryset = Author.objects.prefetch_related('books').all()  # 预加载书籍优化查询
    serializer_class = AuthorDetailSerializer
    lookup_url_kwarg = 'author_id'  # 匹配URL中的参数名

# 处理POST /bookshop/authors/<author_id>/:为该作者创建书籍
class AuthorBookCreateView(CreateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookCreateSerializer
    lookup_url_kwarg = 'author_id'

    def perform_create(self, serializer):
        # 从URL参数获取作者并关联到书籍
        author = Author.objects.get(id=self.kwargs['author_id'])
        serializer.save(author=author)

作者书籍列表视图

# 处理GET /bookshop/authors/<author_id>/book/:获取该作者的书籍
class AuthorBookListView(ListAPIView):
    serializer_class = BookListSerializer
    lookup_url_kwarg = 'author_id'

    def get_queryset(self):
        # 根据URL参数过滤出当前作者的书籍
        return Book.objects.filter(author_id=self.kwargs['author_id'])

2. URL路由配置

在项目urls.py中配置路由,通过请求方法自动匹配对应视图:

from django.urls import path
from .views import (
    AuthorListView,
    AuthorCreateView,
    AuthorDetailView,
    AuthorBookCreateView,
    AuthorBookListView
)

urlpatterns = [
    # 作者列表与创建路由
    path('bookshop/authors/', AuthorListView.as_view(), name='author-list'),
    path('bookshop/authors/', AuthorCreateView.as_view(), name='author-create'),

    # 作者详情与书籍创建路由
    path('bookshop/authors/<int:author_id>/', AuthorDetailView.as_view(), name='author-detail'),
    path('bookshop/authors/<int:author_id>/', AuthorBookCreateView.as_view(), name='author-book-create'),

    # 作者书籍列表路由
    path('bookshop/authors/<int:author_id>/book/', AuthorBookListView.as_view(), name='author-book-list'),
]

补充说明

  • 序列化器需按需定义:比如AuthorDetailSerializer要嵌套BookListSerializer来返回作者关联的书籍;BookCreateSerializer无需包含author字段,由视图自动关联。
  • URL中的参数名author_id需与视图类的lookup_url_kwarg保持一致。
  • DRF会自动根据请求方法,将同一URL的请求分发到对应的视图类。

内容的提问来源于stack exchange,提问作者Saadi Mohammed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 09:25:39