我有模型类BookDetails
和ReaderReviews
。
以下是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)
答案 0 :(得分:1)
它可以简单地
jsondata = json.dumps(dict)
return HttpResponse(jsondata, content_type='application/json')