Hello, I’m trying to display some info from models through views as a list of dictionaries in JSON format but I get the error Object of type QuerySet is not JSON serializable
. How do I fix this?
models.py
class Map(models.Model):
lng = models.FloatField()
lat = models.FloatField()
description = models.TextField(max_length=240)
views.py
from django.http import JsonResponse
def map(request):
data = Map.objects.values('lat', 'lng', 'description')
return render(request, "map.html", JsonResponse({"data": data}))
Why are you trying to pass a JsonResponse
to render
? If you’re rendering it within a template, you probably just want to pass a JSON object to the template.
You also want to convert your queryset to a list before conversion - you want to make sure it’s evaluated before conversion.
This is my 2nd attempt
views.py
def map(request):
data = Map.objects.all()
data = serializers.serialize('json', data, fields=("lat", "lng", "desc"))
return render(request, "map.html", {"data": data})
The output looks like this
"[{"model": "blog.map", "pk": 1, "fields": {"lng": -117.168055, "lat": 33.674921, "desc": "This is some text."}}, {"model": "blog.map", "pk": 2, "fields": {"lng": -117.16793, "lat": 33.68354, "desc": "This is some text."}}]"
However, it should look like this
"[{"lat": "33.674921", "lng": "-117.168055", "desc": "This is some text."}, {"lat": "33.683540", "lng": "-117.167930", "desc": "This is some text."}]"
Yes, because you’re “doing too much” with it.
Try:
def map(request):
data = list(Map.objects.values('lat', 'lng', 'description'))
return render(request, "map.html", {'data': data})
(Edited to fix error with context)
1 Like
Haha you’re so right! This worked though. Thanks Ken.
def map(request):
data = dumps(list(Map.objects.values('lat', 'lng', 'desc')))
return render(request, "map.html", {"data": data})