0

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)
6
  • Does this answer your question? Django Serializing of ValueQuerySet Commented Sep 4, 2020 at 16:56
  • No not really to be honest I'm not sure I understand what the answer shown was telling to do. Commented Sep 4, 2020 at 17:05
  • The answer conveys that you can't serialize a ValueQuerySet (same as in your case) which is an iterable contains dict objects, using Django serializer Commented Sep 4, 2020 at 17:08
  • Oh ok then how can I convert it into JSON? Commented Sep 4, 2020 at 17:09
  • have you tried data = json.dumps(list(titles))? Commented Sep 4, 2020 at 17:11

1 Answer 1

1

What ever for objects in your QuerySet are, still it is a QuerySet. My guess is: you don't want serialize your QuerySet, rather the content, the objects in it. That said: you need to unpack the QuerySet and apply your serialization on each object in it.

example:

from django.contrib.auth.models import User
allUsers = User.objects.all() # QuerySet: allUsers
# apply your operation on each object in QuerySet (users) like this:
serializedData = [ json.dumps({'usrname': user.username, 
                  'mail': user.email}) for user in allUsers]

Your serialized data set is now in serializedData. Problem is, you want do things like this:

serializedData = [ json.dumps(user) for user in allUsers ]

but there is no such thing like a free lunch regarding json.dumps() and your objects, in this example User objects. You have two options:

(1) coding the dict like example above {'usrname': user.username......}) or

(2) you need to define a "class ObjectClassNameEncoder(JSONEncoder):" in case of User object "class UserEncoder(JSONEncoder):", this it's more 'sophisticated'. Bottom line: your path you have to look for: JSONEncoder.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.