How can I serialize a python Dictionary to JSON and pass back to javascript, which contains a string key, while the value is a List (i.e. [])
if request.is_ajax() and request.method == 'GET':
groupSet = GroupSet.objects.get(id=int(request.GET["groupSetId"]))
groups = groupS开发者_如何学Goet.groups.all()
group_items = [] #list
groups_and_items = {} #dictionary
for group in groups:
group_items.extend([group_item for group_item in group.group_items.all()])
#use group as Key name and group_items (LIST) as the value
groups_and_items[group] = group_items
data = serializers.serialize("json", groups_and_items)
return HttpResponse(data, mimetype="application/json")
the result:
[{"pk": 5, "model": "myApp.group", "fields": {"name": "\u6fb4\u9584", "group_items": [13]}}]
while the group_items should have many group_item and each group_item should have "name", rather than only the Id, in this case the Id is 13.
I need to serialize the group name, as well as the group_item's Id and name as JSON and pass back to javascript.
I am new to Python and Django, please advice me if you have a better way to do this, appreciate. Thank you so much. :)
Your 'groups' variable is a QuerySet object, not a dict. You will want to be more explicit with the data that you want to return.
import json
groups_and_items = {}
for group in groups:
group_items = []
for item in group.group_items.all():
group_items.append( {'id': item.id, 'name': item.name} )
# <OR> if you just want a list of the group_item names
#group_items = group.group_items.all().values_list('name', flat=True)
groups_and_items[group.name] = group_items
data = json.dumps(groups_and_items)
What exactly did you want you want your data to look like? The above should give you data
like this :
[{ 'groupA': [{'id': 1, 'name': 'item-1'}],
'groupB': [{'id': 2, 'name': 'item-2'}, ...],
'groupC': []
}]
Or this if you just want the list of group_item names:
[{ 'groupA': ['item-1'],
'groupB': ['item-2', ...],
'groupC': []
}]
You should use Python's json module to encode your JSON.
Also, what indentation level do you have data = serializers
at? It looks like it could be inside the for loop?
精彩评论