我正在寻找一种方法来存储从外部 API 获取的问题,并将其存储在名为
Question
的模型中。我的 views.py
模块通过根据用户的问题难度选择请求数据来实现这一点,然后以表单呈现获取的内容。这是一个非常简单的方法,但由于某种原因我得到了Field 'id' expected a number but got {'type': 'multiple'...}
。
我从这个问题的“最后一个答案”中删除了一个旨在创建另一个干扰此实现的模型单例的代码。然后我运行 ./manage.py makemigrations
和
./manage.py migrate
来反映更改,但再次引发了异常。之后,我删除了migrations.py及其缓存文件来运行相同的两个命令,但没有任何改变。任何人都可以指出我遗漏/做错了什么吗?
模型.py
from django.db import models
class Question(models.Model):
type = models.TextField()
difficulty = models.TextField()
category = models.TextField()
question = models.TextField()
correct_answer = models.TextField()
incorrect_answers = models.TextField()
from django.shortcuts import render, HttpResponse
from .forms import QuestionForm, QuestionLevelForm
from urllib.request import URLError
from .models import Question
import requests
def process_question(request):
if "level" in request.POST:
return fetch_question(request)
elif "answer" in request.POST:
return check_answer(request)
else:
form = QuestionLevelForm()
return render(request, "log/question.html", {"form": form})
def fetch_question(request):
match request.POST["difficulty"]:
case "easy":
url = "https://opentdb.com/api.php?amount=1&category=9&difficulty=easy&type=multiple"
case "medium":
url = "https://opentdb.com/api.php?amount=1&category=9&difficulty=medium&type=multiple"
case "hard":
url = "https://opentdb.com/api.php?amount=1&category=9&difficulty=hard&type=multiple"
try:
response = requests.get(url)
except URLError as e:
HttpResponse("Couldn't fetch data, try again")
else:
render_question(request, response.json())
def render_question(request, response):
content = response["results"][0]
question = {
"type": content["type"],
"difficulty": content["difficulty"],
"category": content["category"],
"question": content["question"],
"correct_answer": content["correct_answer"],
"incorrect_answers": content["incorrect_answers"],
}
form = QuestionForm(question)
model = Question(question)
model.save()
context = {"question": question, "form": form}
render(request, "./log/templates/log/question.html", context)
from django.http import HttpRequest
from django.test import TestCase, Client
from .. import views
client = Client()
class QuestionTest(TestCase):
def test_page_load(self):
response = self.client.get("/log/question")
self.assertEqual(response["content-type"], "text/html; charset=utf-8")
self.assertTemplateUsed(response, "log/question.html")
self.assertContains(response, "Choose your question level", status_code=200)
def test_fetch_question(self):
request = HttpRequest()
request.method = "POST"
request.POST["level"] = "level"
request.POST["difficulty"] = "hard"
request.META["HTTP_HOST"] = "localhost"
response = views.process_question(request)
self.assertEqual(response.status_code, 200)
model
构造函数时,请使用关键字参数
![1] 使用关键字参数,您可以指定要分配给哪些参数。例如:
Question(
type = content["type"],
difficulty = content["difficulty"],
category = content["category"],
question = content["question"],
correct_answer = content["correct_answer"],
incorrect_answers = content["incorrect_answers"]
)
您还可以使用
dict
解包来构造
Question
。这将自动生成参数:Question(**question)
[1] 在您的示例中,class Question
的构造函数采用
question
(它是 dict
)并将其分配给其第一个参数 id
。