python - DRF : how to not allow create() in Serializer

标签 python django django-rest-framework

我正在使用 DRF,并有一个 ViewSet,我希望在其中允许所有可能的操作(列表、详细信息、更新、删除),但 create() 除外。

这就是我目前所拥有的:

class FooViewSet(viewsets.ModelViewSet):

    queryset = Foo.objects.order_by('-date_added').all()
    serializer_class = FooSerializer

    def create(self, request):
        return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)

    def update(self, request, pk=None):
        version = get_object_or_404(Foo, pk=pk)
        html = request.data.get('html')
        version.update_content(html)
        return Response(data={
            'id': version.id,
            'name': version.name,
            'description': version.description,
            'html': version.content,
        }, status=status.HTTP_200_OK)

我知道我可以使序列化器继承自 ReadOnlyModelViewSet 但这样我就无法更新它。

那么不允许create()的最干净的方法是什么?

最佳答案

如上所述in this answer ,您可以通过在任何类 View 中添加 http_method_names 来限制允许的方法。 http_method_names是Django默认 View 类中的一个属性,详细定义见this link .

以您的代码为例,如果您想排除create(引用'post'方法)操作,您可以执行以下操作:

class FooViewSet(viewsets.ModelViewSet):
    queryset = Foo.objects.order_by('-date_added').all()
    serializer_class = FooSerializer
    http_method_names = ['head', 'get', 'put', 'patch', 'delete']

关于python - DRF : how to not allow create() in Serializer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60545403/

相关文章:

python - 防止列表理解中的多次调用

Python - 使用pickle时发生类型错误 - 如何正确使用它

python - 我可以在 Yed-Graphs 上使用 Python 的图算法吗?

python - Django - 注释按日期分组的不同值的 Count()

python - 如何在 django Rest 框架中序列化当前用户?

python - 为用户 auth django 创建用户配置文件

python - Django - 如何过滤管理页面表中可编辑列中的外键选择?

python - 从 django timesince 中删除尾随数据 -- 模板等效项

javascript - 从 Node js 到 django 的 csrf 问题

django - 无法使用 View 名称 (django-rest-framework) 解析超链接关系的 URL