Ed.
Ed.

Reputation: 4597

Convert multiple querysets to json in django

I asked a related question earlier today

In this instance, I have 4 queryset results:

action_count = Action.objects.filter(complete=False, onhold=False).annotate(action_count=Count('name'))
hold_count = Action.objects.filter(onhold=True, hold_criteria__isnull=False).annotate(action_count=Count('name'))
visible_tags = Tag.objects.filter(visible=True).order_by('name').filter(action__complete=False).annotate(action_count=Count('action'))
hidden_tags = Tag.objects.filter(visible=False).order_by('name').filter(action__complete=False).annotate(action_count=Count('action'))

I'd like to return them to an ajax function. I have to convert them to json, but I don't know how to include multiple querysets in the same json string.

Upvotes: 1

Views: 3115

Answers (2)

Keith Entzeroth
Keith Entzeroth

Reputation: 2059

I know this thread is old, but using simplejson to convert django models doesn't work for many cases like decimals ( as noted by rebus above).

As stated in the django documentation, serializer looks like the better choice.

Django’s serialization framework provides a mechanism for “translating” Django models into other formats. Usually these other formats will be text-based and used for sending Django data over a wire, but it’s possible for a serializer to handle any format (text-based or not).

Django Serialization Docs

Upvotes: 3

Simon Steinberger
Simon Steinberger

Reputation: 6825

You can use Django's simplejson module. This code is untested though!

from django.utils import simplejson
dict = {
    'action_count': list(Action.objects.filter(complete=False, onhold=False).annotate(action_count=Count('name')).values()),
    'hold_count': list(Action.objects.filter(onhold=True, hold_criteria__isnull=False).annotate(action_count=Count('name')).values()),
    ...
}
return HttpResponse( simplejson.dumps(dict) )

I'll test and rewrite the code as necessary when I have the time to, but this should get you started.

Upvotes: 1

Related Questions