Brian
Brian

Reputation: 877

How to send django model queryset to template through ajax?

Suppose I have model Abc and Tags which have many to many relation,

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



     data = {}

How do I format my queryset both options and tagsset in data?

Upvotes: 1

Views: 978

Answers (2)

coolharsh55
coolharsh55

Reputation: 1199

Simple answer:

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

Although the question asked only about formatting the return parameters, this answer shows a different way to do the same (which is better IMO for cases where there is more data to be packed and sent. This approach also keeps related data together, i.e. options and related tags are binded together.

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

Upvotes: 0

Aswin Murugesh
Aswin Murugesh

Reputation: 11070

You can put them in a dictionary, convert them to json, and them return the json_object

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

json_object = json.dumps(data)

return HttpResponse(json_object)

This above code will send the json object to the calling ajax method

Upvotes: 1

Related Questions