Django - 我们如何将dict和模型对象发送为json

时间:2015-11-21 01:35:26

标签: python json django

我有模型类BookDetailsReaderReviews

以下是views.py中我的课程,它尝试返回BookDetail信息,并检查登录用户是否已发布有关此书的评论。

user_review是一个dict,用于检查用户是否已发布评论。我想将user_review dict和book_info作为json返回。我不知道如何返回字典和模型数据。

views.py:

class Book(DetailView):
    model = BookDetails
    context_object_name = "bookobject"

    def get_context_data(self, **kwargs):
        context = super(Book,self).get_context_data(**kwargs)
        context['book_reviews'] = ReaderReviews.objects.filter(review_id__exact=str(self.kwargs['pk']))
        return context


    def render_to_response(self, context, **response_kwargs):

        #import pdb; pdb.set_trace()

        #default value for review_flag
        user_review = {"review_flag":'0'}

        #Check if the user already posted review about the book
        for book_review in context['book_reviews']:

            if book_review.user.username == self.request.user.username:
                user_review["review_flag"] = '1'
                break

        #serialize book detail info, all reviews and user review flag dict
        user_review_json = json.dumps(user_review)
        book_info = serializers.serialize('json',list([context['bookobject']])+list(context['book_reviews']))

        data = json.dumps({"review_flag":user_review_json,"book_detail":book_info})


        return JsonResponse(data,encoder=DjangoJSONEncoder, safe=False, **response_kwargs)

1 个答案:

答案 0 :(得分:1)

它可以简单地

jsondata = json.dumps(dict)
return HttpResponse(jsondata, content_type='application/json')