【发布时间】:2021-09-04 08:56:25
【问题描述】:
我是 Django REST 框架的初学者,我正在构建一个应用程序来总结带有标题的文章。我试图从Article 模型中获取信息以传递到Summary 之一。我无法理解在这种情况下使用get_object_or_404(如何实例化模型)以及如何使用pk 参数。我尝试将status URL 更改为status/<int:article_id> 并将article 作为pk 传递,但是在运行POST 请求时我得到了404。我被困在如何使用该论点上。如何正确使用 get_object_or_404 从我的请求中实例化模型?
views.py:
import json
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, JsonResponse
from rest_framework.decorators import api_view
from .models import *
@api_view(['POST'])
def get_summary(request, pk):
article = get_object_or_404(Article, pk=pk)
mdl = Summary()
return JsonResponse(mdl.preprocess(article.content), safe=False)
models.py:
# Article class
class Article(models.Model):
headings = models.CharField(max_length=200)
content = models.CharField(max_length=500000)
# Summary results class (so far)
class Summary(models.Model):
preprocessor = TextPreprocessor()
in_text = models.CharField(max_length=500000)
topics = models.CharField(max_length=200)
def preprocess(self, text):
return self.preprocessor.preprocess(text)
urls.py:
from django.urls import path, include
from rest_framework import routers
from .api import *
from .views import *
router = routers.DefaultRouter()
router.register('my_api', SummaryViewSet, 'api')
urlpatterns = [
path('api/', include(router.urls)),
path('status/', get_summary)
]
【问题讨论】:
标签: python django django-rest-framework