转换多个查询集在Django为JSON [英] Convert multiple querysets to json in django

查看:95
本文介绍了转换多个查询集在Django为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问了一个<一个href="http://stackoverflow.com/questions/9648861/return-multiple-variables-from-an-django-ajax-function">related问题在今天早些时候

在这种情况下,我有4个查询集的结果:

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'))

我想他们返回到AJAX功能。我将它们转换为JSON,但我不知道如何将在同一个JSON字符串多个查询集。

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.

推荐答案

您可以使用Django的simplejson模块。这code是未经考验的,但!

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) )

我会测试和改写code必要时,我有时间,但这应该让你开始。

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

这篇关于转换多个查询集在Django为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆