简体   繁体   中英

How to iterate over queryobject in django?

I want to iterate over Query-object to process and send response accordingly.

This is working JavaScript part

var msg = $.ajax({type: "GET", url: "jsonview/", async: false}).responseText;
document.write(msg);

This is working django views.py

from django.http import JsonResponse
def jsonview(request):
    return JsonResponse({"foo":"bar", "spam" : "no"})

I get the result {"foo": "bar", "spam": "no"}

but I want to do like this (Don't Ask why).

var msg = $.ajax({
                    type: "GET",
                    url: "jsonview/",
                    data:{["foo","spam"]},
                    async: false
                    }).responseText;
  document.write(msg);




def jsonview(request):
      spam_dict = {"foo":"bar", "spam" : "no"}
      new_dict = {}
      for item in request.GET.get('data'):
          new_dict[item] = spam_dict[item]
    return JsonResponse(new_dict)

desired -> {"foo":"bar", "spam" : "no"}

I tried various methods like

for item in request.GET:
for item in request.GET.get('data')

etc.

You don't have a data key in your request; that's just the parameter jQuery uses to pass the data value to the ajax function.

Also note that {["foo","spam"]} in JS evaluates to just ["foo","spam"] ; you can't have an object with no key, it is just an array.

Because this is not form-encoded data, you cannot use request.GET or request.POST in Python. You can read this data from request.body , but it would be better to pass it as JSON and parse it at the other end. So, in JS:

$.ajax({
    type: "POST",
    url: "jsonview/",
    data: JSON.stringify(["foo","spam"]),
    ...
});

and in Python:

data = json.loads(request.body)

request.GET is a dictionary-like object and can be iterated over like any other Python dictionary:

>>> from django.http.request import HttpRequest
>>> req = HttpRequest()
>>> req.GET["test"] = 5
>>> req.GET["test2"] = "pouet"
>>> for key, val in req.GET.items():
...     print(key, val)
... 
test2 pouet
test 5

In few words, just use for key, val in request.GET.items(): to iterate over your dict and get each key and value in key and val variables.

additional notes:

  • for item in request.GET: just iterates over the keys of the dictionary
  • for item in request.GET.get('data'): tries to iterate over a the value associated to the 'data' key in the dict (which does not exist)
  • request.GET.items() returns an iterator fetching each key/value pair in the form of a tuple. You could just retrieve the tuple by storing it in a single variable like this for key_value_pair in request.GET.items(): and then access the key with key_value_pair[0] and the value with key_value_pair[1] . But it is much more convenient to map each value of the tuple in a variable with for key, val in request.GET.items():

You can do this

var msg = $.ajax({
                    type: "POST",
                    url: "jsonview/",
                    data: {"data": ["foo","spam"]},
                    async: false
                    }).responseText;
document.write(msg);

Then in view

for item in request.POST.getlist('data[]'):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM