I'd like to use simplejson to serialize a Django model. Django's serializer doesn't support dictionaries... and simplejson doesn't support Django Querysets. This is quite a conundrum.
In the model there's sponsors that have a Foreign Key to sponsor level, I'm trying to group all the sponsors that belong to a certain sponsor level together. Here's the code that generates the list:
from django.shortcuts import get_list_or_404
from special_event.models import Sponsor, SponsorLevel
sponsor_dict = {}
roadie_sponsors = get_list_or_404(Sponsor, level__category = SponsorLevel.ROADIE_CHOICE)
for item in roadie_sponsors:
try:
sponsor_dict[item.level.name].append(item)
except KeyError:
sponsor_dict[item.level.name] = [item]
这是sponsor_dict
"造"后的样子
{
'Fan': [<Sponsor: Fan Sponsor>],
'VIP': [<Sponsor: VIP Sponsor>],
'Groupie': [<Sponsor: Groupie Sponsor>],
'Silver': [<Sponsor: Silver Sponsor>],
'Bronze': [<Sponsor: Another Bronze Sponsor>, <Sponsor: Bronze Sponsor>]
}
我只在每个级别中添加了一个赞助商,除了铜牌,只是为了展示它是如何工作的.我只想把它"全部"转换成JSON,这样jQuery就可以轻松地解释它.Django的其他序列化程序(如XML或YAML)可以实现这一点吗?我可以"扩展"Django JSON序列化程序来处理字典,还是"扩展"simplejson来处理Django QuerySet对象?