1

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.

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

5 Comments

This won't actually work. You can't serialize a Django queryset like that, because the model instances themselves aren't serializable by the json module directly.
Okay, thanks for the hint! I just re-wrote the code. Now actual lists of dictionaries are created on the fly. It should work - but it's still untested. Maybe it's not the most elegant way ...
You could use values() or values_list() instead of building dictionaries that way, specially since if any of the fields are ForeingKey or something it would again return an unserializable object. json.dumps(list(Model.object.filter().values())) for example.
Not sure would this work for example with decimal fields though.
Thanks, all. I hacked this a bit, but got a working solution off the comments here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.