2

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 ?

4
  • What is the output of print(data) ? Please add it in the question. Commented Jul 19, 2020 at 5:59
  • Done, I can also make it display more than one question but I am keeping it simple for now. Commented Jul 19, 2020 at 6:01
  • The actual data is present inside the data['results'] . Iterate the data['results'] and form the QuestionData . Commented Jul 19, 2020 at 6:04
  • @yogaraj I have done something like data = requests.get(url = request.data['url']).json() quesdata = data['results'] print(quesdata) But have no idea how to proceed with building QuestionData and changing data to the new quesdata doesn'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... Commented Jul 19, 2020 at 6:34

1 Answer 1

1

@Mohammed Adel, Assuming that the QuestionSerializer takes the input data as list of dicts, the below view method will help.

def opendb(request):
    data = requests.get(url=request.data['url']).json()
    questions_to_serialize = []

    for question_data in data.get('results', []):
        QuestionData = {
            "category": question_data.get('category'),
            "type": question_data.get('type'),
            "difficulty": question_data.get('difficulty'),
            "question": question_data.get('question'),
            "answer": question_data.get('correct_answer'),
            "options": question_data.get('incorrect_answers'),
        }
        questions_to_serialize.append(QuestionData)
    
    serializer = QuestionSerializer(data = questions_to_serialize)
    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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.