我试图将JSON响应中的数据添加到数据库中。这是我的models.py
的样子
class Question(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
category = models.ForeignKey(Category, on_delete=models.CASCADE, null=False)
question = models.CharField(max_length=100000, unique=False)
options = models.ManyToManyField("Options")
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
answer = models.ForeignKey(Options, related_name="correct", on_delete=models.CASCADE, null = False)
difficulty = models.CharField(max_length=5000)
type = models.CharField(max_length=2000)
这是我的views.py
的样子
@api_view(['POST'])
def opendb(request):
data = requests.get(url=request.data['url']).json()
print(data)
QuestionData = {
"category": data.get('category'),
"type": data.get('type'),
"difficulty": data.get('difficulty'),
"question": data.get('question'),
"answer": data.get('correct_answer'),
"options": data.get('incorrect_answers'),
}
serializer = QuestionSerializer(data=QuestionData)
if serializer.is_valid():
serializer.save()
return JsonResponse({
"data": serializer.data
}, status=status.HTTP_200_OK)
return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
下面是当我将url发送到此视图时发生的情况
{
"question": [
"This field may not be null."
],
"difficulty": [
"This field may not be null."
],
"type": [
"This field may not be null."
],
"category": [
"This field may not be null."
],
"answer": [
"This field may not be null."
],
"options": [
"This field may not be null."
]
下面是我需要的API如何从返回JSON填充数据
{
"response_code": 0,
"results": [
{
"category": "General Knowledge",
"type": "multiple",
"difficulty": "easy",
"question": "What do the letters in the GMT time zone stand for?",
"correct_answer": "Greenwich Mean Time",
"incorrect_answers": [
"Global Meridian Time",
"General Median Time",
"Glasgow Man Time"
]
}
]
打印(数据)输出以下内容:
{'response_code': 0, 'results': [{'category': 'General Knowledge', 'type': 'multiple', 'difficulty': 'easy', 'question': 'What is the name of the Jewish New Year?', 'correct_answer': 'Rosh Hashanah', 'incorrect_answers': ['Elul', 'New Year', 'Succoss']}]}
这是某种格式问题吗
@Mohammed Adel,假设
QuestionSerializer
将输入data
作为dict列表,下面的视图方法将有所帮助相关问题 更多 >
编程相关推荐