类型为“”的对象不可JSON序列化

时间:2019-08-20 07:56:08

标签: json django django-rest-framework

我试图创建一个API并在Response中传递上下文数据,但出现错误:

  

TakenQuiz类型的对象不可JSON序列化

下面是代码:

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)

以下是上下文数据:

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'}

我认为该错误是由于extra_context中的queryset引起的,我该如何解决呢? 我尝试了json.dumps,但仍然无法正常工作

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

更新

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

2 个答案:

答案 0 :(得分:1)

您需要通过某些序列化程序或调用来序列化take_quizzes对象 “ .values()”并指定所需的键(如果有)(否则它将给出模型的所有值作为字典)

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

答案 1 :(得分:1)

如ruhaib所述,您需要序列化数据。如果我不想为模型定义特殊的序列化器,这就是我要做的。

    from django.core import serializers

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

您可以先执行此操作,然后再用一些数据填充extra_content。