【问题标题】:How to send django model queryset to template through ajax?如何通过ajax将django模型查询集发送到模板?
【发布时间】:2015-11-07 07:48:07
【问题描述】:
假设我有模型 Abc 和 Tags 具有多对多关系,
options = Abc.objects.all()
tagsset = []
for entry in options:
tags_arr = entry.tags_set.all()
if tags_arr:
tagsset.append(tags_arr)
data = {}
如何在数据中格式化我的查询集选项和标签集?
【问题讨论】:
标签:
python
django
python-2.7
django-models
django-views
【解决方案1】:
您可以将它们放入字典中,将它们转换为 json,然后它们返回 json_object
data = {}
data['options'] = options
data['tagsset'] = tagsset
json_object = json.dumps(data)
return HttpResponse(json_object)
上面这段代码会将json对象发送给调用ajax方法
【解决方案2】:
简单的答案:
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
虽然这个问题只询问了格式化返回参数,但这个答案显示了一种不同的方式来做同样的事情(对于有更多数据要打包和发送的情况,这是更好的 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 %}