【问题标题】:Which request to use to fetch data from database based on some data sent?根据发送的某些数据,使用哪个请求从数据库中获取数据?
【发布时间】:2017-08-18 14:10:59
【问题描述】:

我正在使用 django-rest-framework 的 genericAPIViews

我想从前端发送一些数据到后端,根据发送的数据,Django 应该查询一个模型并将一些数据返回到前端。发送的数据是受保护的数据,因此不能附加在 URL 中,因此不能使用 GET 请求。我不是在操作数据库,只是查询它并返回响应(典型的 GET 用例)。

现在在 DRF 的 genericAPIViews 中,我找不到执行此操作的视图:

Tom Christie's GitHub page 可以看出,只有 2 个视图有一个 post 处理程序:

  1. CreateAPIView返回 self.create()
  2. ListCreateAPIView返回 self.create()

可以看出,这两个视图都有 post 方法,可以在数据库中创建我不想要的条目。是否有一个内置类可以完成我的工作,或者我应该使用 generics.GenericAPIView 并编写自己的 post 处理程序?

目前我正在使用具有 post(self, request, *args, **kwargs) 的 generic.View

【问题讨论】:

    标签: api django-views django-rest-framework django-generic-views


    【解决方案1】:

    我认为您有几个选项可供选择。一种方法是使用一个非常有用的 ModelViewSet,因为它可以很好地处理视图、序列化器和模型之间的通信。 Here 是 django-rest-framework ModelViewSet 文档的链接。

    这些是它默认提供的操作(因为它继承自 GenericAPIView):

    .list(), .retrieve(), .create(), .update(), .partial_update(), .destroy().

    如果您不想要所有这些,您可以通过执行以下操作来指定您想要的方法:

    class ModelViewSet(views.ModelViewSet):
        queryset = App.objects.all()
        serializer_class = AppSerializer
        http_method_names = ['get', 'post', 'head']
    

    注意: http_method_names 似乎在 Django >= 1.8 中工作

    来源: Disable a method in a ViewSet, django-rest-framework

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-11
      • 1970-01-01
      • 2013-08-28
      • 1970-01-01
      相关资源
      最近更新 更多