I am trying to add data from a JSON response to my database. Here is what my models.py looks like
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)
Here is what my views.py looks like.
@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)
Here is what happens when i send a url to this view
{
"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."
]
here is how the API i need to fill data from returns 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"
]
}
]
print(data) outputs the following:
{'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']}]}
Is it some sort of formatting problem ?
print(data)? Please add it in the question.data['results']. Iterate thedata['results']and form theQuestionData.data = requests.get(url = request.data['url']).json()quesdata = data['results']print(quesdata)But have no idea how to proceed with buildingQuestionDataand changingdatato the newquesdatadoesn't seem to work. It would be super helpful if you can write this in the original view, been stuck for 2 days on this...