Mohammed Adel
Mohammed Adel

Reputation: 23

JSON Response "This field may not be null." Django Rest Framework

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 ?

Upvotes: 2

Views: 1138

Answers (1)

Yogaraj
Yogaraj

Reputation: 320

@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)

Upvotes: 1

Related Questions