Hi I'm trying to convert a Django queryset object into JSON but every time I try do it with the python JSON module I get this error: "TypeError: Object of type QuerySet is not JSON serializable". Here is the Django object: titles = Queries.objects.values('Topic').distinct(). and here is what it returns `<QuerySet [{'Topic': 'Phone or Web'}, {'Topic': 'Time or Money'}, {'Topic': 'Power or Wisdom'}, {'Topic': 'Luxure or Camp!'}]>.
Now even when I try to use the django serilizers to try to solve this problem I get this error: "AttributeError: 'dict' object has no attribute '_meta'." Can anyone help me solve this? Here is my code for both situation.
code of the django serializers situation:
from django.shortcuts import render
from django.http import HttpResponse
from .models import Queries
import json
from django.core.serializers import json
from django.core import serializers
def data_json():
titles = Queries.objects.values('Topic').distinct()
titles_json = serializers.serialize('json', titles)
with open('topic.json', 'w') as file:
data = json.dumps(titles_json)
print(data, file=file)
print(titles)
def index(request, query_title):
queries = Queries.objects.all()
page = Queries.objects.filter(Topic=str(query_title))
# print(page)
data_json()
return render(request, 'Querie/index.html', {'queries': page})
and here how my code looked like when I was using the regular json module so the data_json funtion was like this:
import json
def data_json():
titles = Queries.objects.values('Topic').distinct()
with open('topic.json', 'w') as file:
data = json.dumps(titles)
print(data, file=file)
ValueQuerySet(same as in your case) which is an iterable containsdictobjects, using Django serializerdata = json.dumps(list(titles))?