Farhan Habib
Farhan Habib

Reputation: 153

How to serialize a django QuerySet and a django object in one call?

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

Answers (2)

Daniel Roseman
Daniel Roseman

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

Farrukh
Farrukh

Reputation: 98

Try this:

context = {
'question': serializers.serialize('json', Question),
'answers' : serializers.serialize('json', answers)
}
return JsonResponse(context, safe=False)

Upvotes: 0

Related Questions