2015-11-21 128 views
0

我有模型類BookDetailsReaderReviewsDjango - 我們如何發送字典和模型對象爲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) 
+0

看起來你已經把他們作爲JSON?出了什麼問題?任何錯誤? – alix

+0

@alix我無法解析jQuery字符串在jQuery Ajax調用中以這種方式返回... – Ranjith

+0

你能分享返回的json嗎? – alix

回答

1

它可以簡單地

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

我同意你的語法..但我在構建模型實例和python字典組合的dict時遇到了困難..有人建議使用django.core.serializers.python來構建字典,它的工作原理! – Ranjith

相關問題