Rahul
Rahul

Reputation: 11520

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.

Upvotes: 0

Views: 184

Answers (3)

Tryph
Tryph

Reputation: 6209

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():

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599480

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)

Upvotes: 1

itzMEonTV
itzMEonTV

Reputation: 20339

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[]'):

Upvotes: 0

Related Questions