Reputation: 23
I have model classes BookDetails
and ReaderReviews
.
Here is my class in views.py
that tries to return BookDetail
info and also checks if the logged-in user already posted a review about this book.
user_review
is a dict which checks if the user already posted a review. I would like to return user_review
dict and book_info
as json. I am not sure how to return the dict and model data.
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)
Upvotes: 0
Views: 330
Reputation: 37846
it can be simply
jsondata = json.dumps(dict)
return HttpResponse(jsondata, content_type='application/json')
Upvotes: 1