Django error serilaizing output of query into JSON - django

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")

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 ?

stringreplace on Django

I need to do the 'string replace' on all my queryset, but I receive the following error:
'QuerySet' object has no attribute 'replace'
def get_profilesJson_view(self):
queryset = Reports.objects.all().values('val_x','val_y').order_by('-time_end')[:1]
new_queryset = queryset.replace(';', ',')
reports_list = list(new_queryset)
return JsonResponse(reports_list, safe=False)
How can I do?
Is it possible to use the '.filter' function? I have not experience with Django
You will need to use Func() to achieve this. You'll need something like this:
def get_profilesJson_view(self):
queryset = Reports.objects.all().update(field_in_queryset_you_want_to_replace=Func(F('string_field'),
Value(';'), Value(','),
function='replace')
Compare with this answer.

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

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)

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)]))

How can i return single object from Django view to Jquery

If i use this
data = serializers.serialize('json', Book.objects.all())
return HttpResponse(data, mimetype='application/javascript') # Redirect after POST
Then i get json objects
but if i need to return single object
then i get error
data = serializers.serialize('json', singleObject)
return HttpResponse(data, mimetype='application/javascript') # Redirect after POST
The error says
object is not iterable
Read the docs on serialization
The arguments to the serialize
function are the format to serialize
the data to (see Serialization
formats) and a QuerySet to serialize.
(Actually, the second argument can be
any iterator that yields Django
objects, but it'll almost always be a
QuerySet).
And then try like this:
data = serializers.serialize('json', [singleObject])
Also, this thread answers your question.
You can use filter instead of get to return single object.