Rodany Antoine
Rodany Antoine

Reputation: 9

how to convert Django object into json?

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)

Upvotes: 0

Views: 5209

Answers (1)

harry hartmann
harry hartmann

Reputation: 361

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.

Upvotes: 1

Related Questions