H C
H C

Reputation: 1200

How to pass a dict of queryset results to $.json?

Currently I have the following queryset filters:

def grab_city_landmark(request):
    State = State.objects.filter(state=state_name)
    City = list(State.valued_list('city', flat=True).distinct())
    Landmark = list(State.valued_list('landmark', flat=True).distinct())

    response = {
         'state': State,
         'city': City,
         'landmark': Landmark,
     }
     return HttpResponse(response, content_type="application/javascript")

The JQuery call is:

 $(document).ready(function() {
      $.getJSON('grab_city_landmark/', {state_name: state}, function(data) {

      ... GRAB DATA HERE ...

      iterate over i
      data['city'][i]

My questions are:

  1. How do I make the response in json form? Is it in json form? How do I check? I can't see the object return to jquery. json.dumps(response) doesn't seem to work.

  2. How do you take a look in java console what is returned to the jquery?

Upvotes: 0

Views: 92

Answers (2)

user8060120
user8060120

Reputation:

You may try to use Django serialization or DRF serializers, second way may help you create rest api. For example:

from django.core import serializers

state = State.objects.filter(state=state_name)
state_data = serializers.serialize("json", state)
city_data = serializers.serialize(
            "json",
            state.distinct('city').order_by(), fields=('city')
            )

Upvotes: 1

Exprator
Exprator

Reputation: 27513

import json

response  = json.dumps(list(State),City,Landmark)
return HttpResponse(response, content_type="application/javascript")

or use the jsonresponse of django

from django.http import JsonResponse
response = JsonResponse({'state': list(State),'city': City,'landmark': Landmark,})

Upvotes: 0

Related Questions