在django中将多个查询转换为json [英] Convert multiple querysets to json in django

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

问题描述

我今天早些时候询问了相关问题

I asked a related question earlier today

在这种情况下,我有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模块。这段代码是未经测试的!

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.

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

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