如何在django中的AJAX请求中返回多个JSON对象

如何在django中的AJAX请求中返回多个JSON对象,django,json,jquery,Django,Json,Jquery,目前,我有一个视图,我将其渲染为模板并返回两个查询列表。我的观点如下所示 def view_notifications(request,user_id): context_instance=RequestContext(request) user = User.objects.get(pk=user_id) user.profile.notifications = 0 user.profile.save() notices = list(notifi

目前,我有一个视图,我将其渲染为模板并返回两个查询列表。我的观点如下所示

def view_notifications(request,user_id):

    context_instance=RequestContext(request)
    user = User.objects.get(pk=user_id)

    user.profile.notifications = 0
    user.profile.save()

    notices = list(notifications.objects.filter(n_reciever=user.id, is_read=0).order_by('-time'))
    number = notifications.objects.filter(n_reciever=user.id, is_read=0).order_by('-time').count()

    if number < 5:
        old_notices = list(notifications.objects.filter(n_reciever=user.id, is_read=1).order_by('-time')[:5])
    else:
        old_notices = False

    notifications.objects.all().update(is_read = 1)

    return render_to_response('profiles/notifications.html', {'New_Notice': notices, 'Old_Notices':old_notices, 'number': number,},context_instance=RequestContext(request))
但是我可以用这种方式发送两个对象列表吗?我也不知道如何在html中显示这个JSON编码的对象列表。我可以像访问模板中的对象一样访问它吗


请帮助

您想发送一个列表,由两个元素组成,每个元素对应一个列表。您可以通过先序列化到Python,然后将全部内容转储到JSON来实现这一点

data1 = serializers.serialize('python', notifications.objects.all())
data2 = serializers.serialize('python', foobar.objects.all())

data = simplejson.dumps([data1, data2])

(或者你可以使用字典,如果在javascript中按键查找会更容易。)

我会启动一个空列表,循环浏览通知,并在列表中附加一个包含所有必需属性的dict。例如,您的
新通知列表可能如下所示:

[{'absolute_url': 'blah', 'url_name': 'blah', 'message': 'blah', 'type': 'blah'},
 {'absolute_url': 'foo', 'url_name': 'foo', 'message': 'foo', 'type': 'foo'}]
为每组通知(旧通知和新通知)创建列表后,您可以发送它们:

from django.utils import simplejson
from django.http import HttpResponse
...
json = simplejson.dumps({'old': old_notices, 'new': new_notices})
return HttpResponse(json, mimetype='text/json')

哇,比我要发布的内容好多了,尽管你肯定想使用字典而不是列表。这会捕获外键上的方法吗,例如
notice.n\u sender.profile.get\u absolute\u url
?按键查找肯定会更容易,我是Python新手,所以你能告诉我如何制作字典吗?其次,我确实需要外键的完整对象。在这种情况下,我需要遍历
n\u sender
的整个对象,我将遍历模型并手动创建字典,确保您拥有所需的所有属性。(正如我在回答中所建议的)您还可以告诉我如何在AJAX成功调用中访问这些对象并将它们添加到适当的html标记中吗?另一件事是,对于
n\u sender
,我可能不需要整个对象,但我需要get\u absolute\u url和发件人的几个其他字段。我知道我需要添加到我正在发送的字典中,但是如何将这些值附加到我获得的
query\u集
。您能告诉我如何构造一个字典,其中包含查询集的名称-值对和来自同一字典中相应的
n\u发送方
对象的所需名称-值对吗
[{'absolute_url': 'blah', 'url_name': 'blah', 'message': 'blah', 'type': 'blah'},
 {'absolute_url': 'foo', 'url_name': 'foo', 'message': 'foo', 'type': 'foo'}]
from django.utils import simplejson
from django.http import HttpResponse
...
json = simplejson.dumps({'old': old_notices, 'new': new_notices})
return HttpResponse(json, mimetype='text/json')