Reputation: 153
I am trying to retrieve my object and a query set from my model through an ajax call. What I want to get back is an object and a query set. So when i serialize the object its no problem but the QuerySet does not seem to be serialized by Django. I get an error "QuerySet has no attribute _meta".
Here is my code:
def followUp(request):
fid = request.GET['fid']
fup = FollowUp.objects.get(answer=fid)
Question = fup.question
answers = Question.answer_set.all()
context = {
'question': Question,
'answers' : answers
}
data = serializers.serialize('json', context)
return JsonResponse(data, safe=False, content_type="application/json")
Here if i just put 'Question' its no problem but as soon as i try to make a dict with 'answers' combined, it throws the error.
Is there a way to serialize both of them or what should I do if not? Please Help!
Upvotes: 0
Views: 990
Reputation: 599450
You shouldn't be using JsonResponse with a serializer anyway, as this means you serialize to JSON twice.
What you should do here is to serialize each of those objects separately, to Python structures, then send that to JsonResponse.
context = {
'question': serializers.serialize('python', [fup.question])[0],
'answers' : serializers.serialize('python', answers)
}
return JsonResponse(context , safe=False)
Note that this is not really a good way of doing things, and if you are trying to do complex serialization you should really use Django REST Framework.
Upvotes: 2
Reputation: 98
Try this:
context = {
'question': serializers.serialize('json', Question),
'answers' : serializers.serialize('json', answers)
}
return JsonResponse(context, safe=False)
Upvotes: 0