【问题标题】:How to call CreateApiView and ListApiView using same url conf in django-rest-framework?如何在 django-rest-framework 中使用相同的 url conf 调用 CreateApiView 和 ListApiView?
【发布时间】:2018-07-26 11:35:30
【问题描述】:

我正在尝试构建一个GETPOST 方法来获取和保存一些对象。 我有views.py这样的

class QuestionList(generics.ListAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

class QuestionSave(generics.CreateAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

然后我有 url conf,urls.py 像这样

urlpatterns = [
    url(r'^questions/$',views.QuestionList.as_view())
    ]

据我了解,我们必须有一个泛型类,其中 CreateApiView 用于 POST 方法,ListApiView 用于GET 方法,所以我创建了这样的类。 我的问题是,我应该如何配置它们以便在 POST QuestionSave 将被调用并在 GET QuestionList 将被调用?

【问题讨论】:

  • 为什么不QuestionList(generics.ListAPIView, generics.CreateAPIView)

标签: python django django-rest-framework django-views


【解决方案1】:

使用 ListCreateAPIView。它为视图提供 get 和 post 方法处理程序。

参考:Django Rest Framework

class QuestionView(generics.ListCreateAPIView)
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

【讨论】:

  • 感谢您的回答,它有效,但现在我收到“此字段是必需的”错误。你能帮我解决这个问题吗?
  • 当然。发布模型的序列化程序和模型的代码
  • 当您没有在发布请求中发送特定字段时,会引发“此字段是必需的”错误,但在您的模型或序列化程序中是必需的。
【解决方案2】:

简单!:

class QuestionList(generics.ListAPIView, generics.CreateAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

【讨论】:

    猜你喜欢
    • 2022-06-14
    • 2013-05-21
    • 2016-06-17
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    • 2016-05-07
    • 2021-04-29
    相关资源
    最近更新 更多