How to encode a django query set specific field to a Json response? - django

I do a filter to obtain a particular set of objects from django data model. I need to encode only a single field of that objects to a json response.
e.g.: Item has an attribute called name.
qs_available = Item.objects.filter(Type=1).values.('name').???
return HttpResponse(json.dumps(qs_available), content_type='application/json')
How do I return the list of name values as a json response?

If you want to get only names list, you can use values_list
qs_available = list(Item.objects.filter(Type=1).values_list('name', flat=True))
return HttpResponse(json.dumps(qs_available), content_type='application/json')

You could use JsonResponse from django.http,
from django.http import JsonResponse
qs_available = Item.objects.filter(Type=1).values_list('name')
return JsonResponse(list(qs_available), safe=False)

Related

Get data from JsonResponse in django

I wanted to know how to get data from a JsonResponse in django. I made a JsonResponse that works like this
def pfmdetail(rsid):
snpid = parseSet(rsid)
if not snpid:
return HttpResponse(status=404)
try:
data = SnpsPfm.objects.values('start', 'strand', 'type', 'scoreref', 'scorealt',
rsid=F('snpid__rsid'), pfm_name=F('pfmid__name')).filter(snpid=snpid[0])
except SnpsPfm.DoesNotExist:
return HttpResponse(status=404)
serializer = SnpsPfmSerializer(data, many=True)
return JsonResponse(serializer.data, safe=False)
and then I call directly the method like this
def pfmTable(qset,detail):
source = pfmdetail(detail)
print(source)
df = pd.read_json(source)
but it gives me an error. I know it's wrong because with the print it returns the status of the response which is 200 so I suppose that the response is fine but how can I access the data inside the response? I tried import json to do json.load but with no success. I even tried the methods of QueryDict but stil I can't acess to the content I'm interested
P.S. I know that data contains something because if i display the jsonresponse on the browser i can see the JSON
As you can see here: https://docs.djangoproject.com/en/2.2/ref/request-response/#jsonresponse-objects.
JsonResponse object holds json in its content attribute.
So to access it try this:
df = pd.read_json(source.content)
Or to see it printed do:
print(source.content)
If you aren't using pandas, then you should process the content attribute of the JSONResponse object like this:
r = json.loads(source.decode())
I got the answer here: How to parse binary string to dict ?

Converting result of MySQL query in Django to JSON

So I query my database using a mySQL query like so:
cursor = connection.cursor()
cursor.execute("select winner,count(winner) as count from DB")
data = cursor.fetchall()
Now I want to send the table in data to my app (as a GET request) in JSON. Doing this is not sending a properly formatted JSON response and I am unable to parse it on the client side.
return HttpResponse(json.dumps(data), content_type='application/json;charset=utf8')
The json.dumps(data) returns this:
[["John Doe", 45]]
Any help in this regard would be appreciated.
The JSON is properly formatted, but you are dumping a list, you should dump a dictionary instead... something like:
myData = {'people': data}
json.dumps(myData)
The point is this: a valid json response must start and end with curly braces, so in order to serve a valid json you have to dump a Python dictionary object as a "root object"... in other words you need at least an object with a key.
From http://json.org
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed
list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
from django.core import serializers
json_data = serializers.serialize('json', data)
return HttpResponse(json_data, mimetype='application/json')
However not everything can be serialized like this into JSON, some things need a custom encoder
You should use a model and the ORM instead of writing your own SQL.
You could easily convert your statement to this simple model and succinctly ORM call.
class Winner(models.Model):
name = models.CharField()
and your database call would now be Winner.objects.all() which would give all winners
and with the count
Winner.objects.annotate(wins=Count('name'))
from django.http import JsonResponse
from django.db import connections
from django.http import HttpResponse
import json
def testRawQuery(request):
cursor = connections['default'].cursor()
cursor.execute("select winner,count(winner) as count from DB")
objs = cursor.fetchall()
json_data = []
for obj in objs:
json_data.append({"winner" : obj[0], "count" : obj[1]})
return JsonResponse(json_data, safe=False)

Converting only one entry of django model object to json

I have a model Y with 3 fields. In this model Y, I have 5 entries.
I know that I can use:
from django.core import serializers
def aMethodThatReturnsJson():
return HttpResponse(serializers.serialize("json", Y.objects.all()))
This returns a proper json response.
But when I change the method to return only 1 row from the model, like below, I get Model Y is not iterable error:
def returnOnlyOneRow():
return HttpResponse(serializers.serialize("json", Y.objects.get(pk=1)))
Why does this not return a proper json object? What is the correct way to do it?
Thanks.
Here is the way to do it:
from django.core import serializers
def return_only_one_row():
return HttpResponse(serializers.serialize("json", Y.objects.filter(pk=1)))
Using filter() instead of get() returns the proper JSON response.
Another way to do it would be to use Python lists. You can wrap the query in [ ] to turn the resulting response to a list and then serialize it to JSON. Example follows:
def return_only_one_row():
return HttpResponse(serializers.serialize("json", [Y.objects.get(pk=1)]))

Django error serilaizing output of query into JSON

Hi
I am trying to use Django to make a page that will search a database fro a certain keyword, I have managed to search the database for the keyword, but now I need to serialize the data into a JSON formatted array so I can use it on the client side using JavaScript.
When I try to serialize my result array I get this error:
'dict' object has no attribute '_meta'
My code looks like this:
def SearchItems(request, itemName):
items_list = list(Item.objects.filter(name = itemName).values())
json_serializer = serializers.get_serializer("json")()
data = json_serializer.serialize(items_list, ensure_ascii=False)
return HttpResponse(data)
Any help would be greatly appreciated,
RayQuang
Instead of using serializer, trying doing this:
return HttpResponse(simplejson.dumps(items_list),'application/json'))
see this answer for more info
do not convert an object to the dict.
simply pass a queryset to the serializer:
json_serializer.serialize(Item.objects.filter(name=itemName), ensure_ascii=False)
alternatively, you can use json/cjson/anyjson serializer directly:
import anyjson
HttpResponse(anyjson.serialize(Item.objects.filter(name=itemName).values()), content_type="application/json")

Serializing Django Model Instances (querysets with values tag)

I am trying to serialize the following view
def headerimage(request):
service_view = list( Service_images.objects.filter(service='7'))
return render_to_response ('headerimage.html',{'service_view':service_view}, context_instance=RequestContext(request))
This is supposed to return JSON in the form shown below
{"folderList":
["with schmurps"],
"fileList":
["toto006.jpg",
"toto012.jpg",
"toto013.jpg"
]
}
However, The folder list can be one or in this case will be "7" given that is the title("folder") of the images.
After taking into account the answer below, I came up with
def headerimage(request):
service_view = Service_images.objects.filter(service='7')
image = serializers.serialize("json", service_view)
mini = list(serializers.deserialize("json", image))
return HttpResponse(image, mimetype='application/javascript')
however, I am still looking for the simplest way to do this
service_view = Service_images.objects.filter(service='7').values('image')
The problem is that the django serializer expects whole models
Service_images.objects.filter() will return a QuerySet object for you, so basically wrapping this into list() makes no sense...
Look at the docs: http://docs.djangoproject.com/en/dev/topics/serialization/#id2, and use LazyEncoder definied there.
I usually follow the below way, when the json format requirement does not match with my model's representation.
from django.utils import simplejson as json
def headerimage(request):
service_view = Service_images.objects.filter(service='7')
ret_dict = {
"folderList":
[sv.image.folder for sv in service_view],
"fileList":
[sv.image.file for sv in service_view]
}
return (json.dumps(ret_dict), mimetype="application/json")