0
我有模型類BookDetails
和ReaderReviews
。Django - 我們如何發送字典和模型對象爲json
這是我的班級views.py
,它試圖返回BookDetail
信息,並檢查登錄用戶是否已發佈有關本書的評論。
user_review
是一個字典,它檢查用戶是否已發佈評論。我想返回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)
看起來你已經把他們作爲JSON?出了什麼問題?任何錯誤? – alix
@alix我無法解析jQuery字符串在jQuery Ajax調用中以這種方式返回... – Ranjith
你能分享返回的json嗎? – alix