Skip to main content
 首页 » 编程设计

python之我如何将 Django 中的 ListCreateAPIView 和 RetrieveUpdateDestroyAPIView 组合成一个支持所有四个 CRUD 操作的 View

2024年08月26日26www_RR

我想知道如何获得可以处理模型所有操作的单点。以及为什么 Django RESTFramework 首先没有可用的泛型?我认为它在其他框架中很常见。

class ItemView(ListCreateAPIView, RetrieveUpdateDestroyAPIView): 
    """ 
    List all items(GET without id), List single item(GET with id),  
    create an item(POST) or update an item(PUT with id) 
    """ 

如果指定了 id,这个 View 类应该在普通 GET 请求和特定项目上返回项目列表。同样,仅当 id 存在时才更新和删除特定项目。

请您参考如下方法:

我认为最好的方法是使用 django rest framework viewsets .例如,您可以定义 ModelViewSet,它将为您的模型组合所有 CRUD 方法。