答案很简单:
data = {}
data['options'] = options
data['tagset'] = tagset
# NOTE: since you skip empty tag sets,
# len(tagset) <= len(options)
# so if you are going to match tagsets with options in the
# browser, they may not match length-wise
虽然问题只问格式化返回参数,但这个答案显示了一种不同的方式来做山姆e(对于需要打包和发送更多数据的情况,IMO更好。这种方法还将相关数据保存在一起,即将选项和相关标签绑定在一起。
# payload is the data to be sent to the browser
payload = []
# get all options and associated tags
# this will be a list of tuples, where each tuple will be
# option, list[tags]
for option in Abc.objects.all():
payload.append((
option, # the option
list(option.tags_set.all()), # list of linked tags
))
# return this payload to browser
return HttpResponse(
# good practice to name your data parameters
json.dumps({ 'data': payload, }),
# always set content type -> good practice!
content_type='application/json'
)
# in the browser template, you can do something such as:
{% for option, tags in data %}
{{ option.something }}
{% for tag in tags %}
{{ tag.something }}
{% endfor %}
{% endfor %}