Rahul Sharma
Rahul Sharma

Reputation: 2495

Object of type "" is not JSON serializable

I am trying to create an API and pass the context data in Response but I am getting the error:

Object of type TakenQuiz is not JSON serializable

Below is the code:

taken_quizzes = quiz.taken_quizzes.select_related('supplier__user').order_by('-date')
total_taken_quizzes = taken_quizzes.count()
quiz_score = quiz.taken_quizzes.aggregate(average_score=Avg('score'))
least_bid = quiz.taken_quizzes.aggregate(least_bid=Min('least_bid'))

extra_context = {'taken_quizzes': taken_quizzes, 
'total_taken_quizzes': total_taken_quizzes,
'quiz_score': quiz_score, 'least_bid': least_bid, 'matching_bids': matching_bids,
'driver_num': driver_num, 'lat_lon_orig': lat_lon_orig, 'lat_lon_dest': lat_lon_dest,
'user_pass': user_pass, 'username': username, 'password': password, }


print("extra content is ", extra_context)

return Response(extra_context)

Here is the context data:

extra content is  {'taken_quizzes': <QuerySet [<TakenQuiz: TakenQuiz object (1)>]>, 'total_taken_quizzes': 1, 'quiz_score': {'average_score': 0.0}, 'least_bid': {'least_bid': 899}, 'matching_bids': [], 'driver_
num': 0, 'lat_lon_orig': '36.1629343, -95.9913076', 'lat_lon_dest': '36.1629343, -95.9913076', 'user_pass': ('jkcekc', 'efce'), 'username': 'efw', 'password': 'sdf'}

The error I believe is because of the queryset in the extra_context, How do I resolve this ? I tried json.dumps but it still doesn't work

Serializer.py

class takenquizSerializer(serializers.ModelSerializer):
    class Meta:
        model = TakenQuiz
        fields = "__all__"

Models.py

class TakenQuiz(models.Model):
    supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, related_name='taken_quizzes')
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='taken_quizzes')
    score = models.FloatField()
    date = models.DateTimeField(auto_now_add=True)
    least_bid = models.IntegerField(default=0)
    confirmed = models.CharField(max_length=100, default='Not Confirmed')

UPDATE

taken_quizzes = quiz.taken_quizzes.select_related('supplier__user').order_by('-date')
taken_quizzs = takenquizSerializer(taken_quizzes).data

Upvotes: 1

Views: 4117

Answers (2)

ruhaib
ruhaib

Reputation: 649

You need to serialize taken_quizzes objects either via some serializer or calling ".values()" and specifying the required key, if any (otherwise it will give all values of the model as a dictionary)

{
    'taken_quizes': TakenQuizSerializer(taken_quizzes, many=True).data,
    # or
    'taken_quizzes': taken_quizzes.values(),
    ....
}

Upvotes: 1

jeph
jeph

Reputation: 82

as ruhaib mentioned you need to serialize the data. If i dont want to define special serializers for models this is what I do.

    from django.core import serializers

    taken_quizzes=....
    data=serializers.serialize('json',taken_quizzes)

you can do this before you populate extra_content with some data.

Upvotes: 1

Related Questions