簡體   English   中英

如何通過ajax將Django模型查詢集發送到模板?

[英]How to send django model queryset to template through ajax?

假設我有模型Abc和標簽,它們之間有很多關系,

    options = Abc.objects.all()
    tagsset = []
    for entry in options:
        tags_arr = entry.tags_set.all()
    if tags_arr:
        tagsset.append(tags_arr)



     data = {}

如何格式化數據中的查詢集和選項集?

您可以將它們放入字典中,將其轉換為json,然后它們返回json_object

data = {}
data['options'] = options
data['tagsset'] = tagsset

json_object = json.dumps(data)

return HttpResponse(json_object)

上面的代碼將json對象發送到調用的ajax方法

簡單答案:

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 %}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM