Menu Close

How to convert Django Queryset to JSON

Convert Django QuerySet to JSON

Hi Django Developers, I hope you are doing well. In this article, I’m gonna show you how to convert Django QuerySet to JSON ( JavaScript Object Notation ) data. Django is one of the most popular Python frameworks that has been gaining more popularity for the past few years. Apart from the web application, Django is used to create the APIs ( Application Programming Interface ) and APIs JSON plays the most important role.

This is one of the most important concepts especially when you are going to work Django API developer or you are working as a Django API developer already because during the API development most of the work is done by JSON data. In this guide, we will explore multiple ways to convert a Django QuerySet to JSON.

As a Django developer, you should have knowledge of the process to convert QuerySet in Django to JSON Object. Before going to this article we will discuss a little bit about Django QuerySet and JSON.

As we know, It is not possible to perform communication between client and server or vice-versa using Django QuerySet that’s why JSON comes into the picture because it enables you to send data to the server or receive data from the server.

What is Django QuerySet?

In the Django framework, QuerySet is a collection of Django model instances. Django Model is basically a Python class that is subclass of django.db.models.Model class. Each Django model represents a single database table and each attribute of the Django model represents the column in the table.

For example, We have a Django model called People and this model has some data in the database as you can see below examples.

Example: Django Model


class People(models.Model):
    first_name = models.CharField(max_length=40, db_column="first_name", verbose_name="First Name")
    last_name = models.CharField(max_length=20, db_column="last_name", verbose_name="Last Name")
    age = models.IntegerField(db_column="age")

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

Example: Django QuerySet

>>> People.objects.all()                
<QuerySet [<People: John Doe>, <People: Harshita kumari>, <People: Jackson Jack>, <People: Mariya Walker>, <People: Vishvajit Rao>, <People: Steve Jobs>, <People: Ratan Tata>, <People: Elon Musk>, <People: Sunder Pichai>, <People: Mark Zuckerburk>]>

What is JSON ( JavaScript Object Notation )?

JSON stands for JavaScript Object Notation. JSON is a text-based data format that is used to store and transmit data. JSON is often used when data send to the server by the client to be processed or data send to the client from the server to be displayed or processed.

JSON stores the data in the form of key/value pairs just like Java Script objects.JSON is essential nowadays because data in the JSON format is easier to travel between client and server.

As we know that Django does not provide any direct ways to convert Django Query set to JSON ( JavaScript Object Notation ) but still we have some options to convert any QuerySet into JSON.

Ref:- Click Here

Example: Sample JSON Data


[
	{
		name: "vishvajit",
		age: 22
	},
	{
		name: "Vikas",
		value: 20
	},
	{
		name: "Vaibhav",
		value: 25
	},
]

How to convert Django QuerySet to JSON

Here we will various ways to change Django QuerySet to JSON ( JavaScript Object Notation ) even though we will see a custom way to convert QuerySet to JSON.

As a developer, you should have knowledge of multiple ways to convert QuerySet in Django to JSON so that you can use any one of them according to your requirement.

Let’s discuss all those methods one by one with the help of the proper example.

Convert Django QuerySet to JSON using JsonResponse

Django provides various types of response classes and JsonResponse is one of them which is used to convert any Django QuerySet to a JSON object. JsonResponse class defined inside django.http package. let’s see how can we convert QuerySet to JSON.

Example:- Convert Django QuerySet to JSON using JsonResponse


>>> from django.http import JsonResponse
>>> from myapp.models import People
>>> data = People.objects.values()
>>> json_data = JsonResponse({"data": list(data)})
>>> json_data.content
b'{"data": [{"id": 2, "first_name": "John", "last_name": "Doe", "gender": "Male", "age": 28}, {"id": 3, "first_name": "Harshita", "last_name": "kumari", "gender": "Female", "age": 22},
 {"id": 4, "first_name": "Jackson", "last_name": "Jack", "gender": "Male", "age": 29}, {"id": 5, "first_name": "Mariya", "last_name": "Walker", "gender": "Female", "age": 30}, {"id": 6
, "first_name": "Vishvajit", "last_name": "Rao", "gender": "Male", "age": 24}, {"id": 7, "first_name": "Steve", "last_name": "Jobs", "gender": "Male", "age": 56}, {"id": 8, "first_name
": "Ratan", "last_name": "Tata", "gender": "Male", "age": 84}, {"id": 9, "first_name": "Elon", "last_name": "Musk", "gender": "Male", "age": 51}, {"id": 10, "first_name": "Sunder", "last_name": "Pichai", "gender": "Male", "age": 50}, {"id": 11, "first_name": "Mark", "last_name": "Zuckerburk", "gender": "Male", "age": 38}]}'

Serialize non-dictionary object

When you want to serialize a non-dictionary object through JsonResponse, then you must have to pass safe=False in JsonResponse.

Example


>>> data = People.objects.values_list("age")       
>>> data
<QuerySet [(28,), (22,), (29,), (30,), (24,), (56,), (84,), (51,), (50,), (38,)]>
>>> data = People.objects.values_list("age", flat=True) 
>>> data
<QuerySet [28, 22, 29, 30, 24, 56, 84, 51, 50, 38]>
>>> json_data = JsonResponse(list(data), safe=False) 
>>> json_data.content
b'[28, 22, 29, 30, 24, 56, 84, 51, 50, 38]'

Convert Django QuerySet to JSON using Django Django Serializers

Django provides a function called serializer that is defined inside django.core.serializers package. serialize function takes “JSON” which represents the content type of output and the second is Django QuerySet and returns converted JSON data.

Example


>>> from django.core.serializers import serialize
>>> from myapp.models import People 
>>> data = People.objects.all()
>>> json = serialize("json", data)
>>> json
'[{"model": "myapp.people", "pk": 2, "fields": {"first_name": "John", "last_name": "Doe", "gender": "Male", "age": 28}}, {"model": "myapp.people", "pk": 3, "fields": {"first_name": "Harshita", "last_name": "kumari", "gender": "Female", "age": 22}}, {"model": "myapp.people", "pk": 4, "fields": {"first_name": "Jackson", "last_name": "Jack", "gender": "Male", "age": 29}}, {"model": "myapp.people", "pk": 5, "fields": {"first_name": "Mariya", "last_name": "Walker", "gender": "Female", "age": 30}}, {"model": "myapp.people", "pk": 6, "fields": {"first_n
ame": "Vishvajit", "last_name": "Rao", "gender": "Male", "age": 24}}, {"model": "myapp.people", "pk": 7, "fields": {"first_name": "Steve", "last_name": "Jobs", "gender": "Male", "age":
 56}}, {"model": "myapp.people", "pk": 8, "fields": {"first_name": "Ratan", "last_name": "Tata", "gender": "Male", "age": 84}}, {"model": "myapp.people", "pk": 9, "fields": {"first_nam
e": "Elon", "last_name": "Musk", "gender": "Male", "age": 51}}, {"model": "myapp.people", "pk": 10, "fields": {"first_name": "Sunder", "last_name": "Pichai", "gender": "Male", "age": 50}}, {"model": "myapp.people", "pk": 11, "fields": {"first_name": "Mark", "last_name": "Zuckerburk", "gender": "Male", "age": 38}}]'

Convert Django QuerySet to JSON using values() method

Django QuerySet provides a method called values() that is used to get the collection of Django Model’s instances and each instance inside a list represents the dictionary of the Django model. values() method is also capable of converter any QuerySet in Django to a JSON object.

Example:


>>> data = People.objects.all().values()
>>> data
<QuerySet [{'id': 2, 'first_name': 'John', 'last_name': 'Doe', 'gender': 'Male', 'age': 28}, {'id': 3, 'first_name': 'Harshita', 'last_name': 'kumari', 'gender': 'Female', 'age': 22}, 
{'id': 4, 'first_name': 'Jackson', 'last_name': 'Jack', 'gender': 'Male', 'age': 29}, {'id': 5, 'first_name': 'Mariya', 'last_name': 'Walker', 'gender': 'Female', 'age': 30}, {'id': 6,
 'first_name': 'Vishvajit', 'last_name': 'Rao', 'gender': 'Male', 'age': 24}, {'id': 7, 'first_name': 'Steve', 'last_name': 'Jobs', 'gender': 'Male', 'age': 56}, {'id': 8, 'first_name'
: 'Ratan', 'last_name': 'Tata', 'gender': 'Male', 'age': 84}, {'id': 9, 'first_name': 'Elon', 'last_name': 'Musk', 'gender': 'Male', 'age': 51}, {'id': 10, 'first_name': 'Sunder', 'last_name': 'Pichai', 'gender': 'Male', 'age': 50}, {'id': 11, 'first_name': 'Mark', 'last_name': 'Zuckerburk', 'gender': 'Male', 'age': 38}]>

By default, the values() method returns all the fields but sometime it might be your requirement to select some specific fields, Then you can pass all those fields separately in the values() method. For example, I want to access only first_name and last_name


>>> data = People.objects.values("first_name", "last_name")
>>> data
<QuerySet [{'id': 2, 'first_name': 'John', 'last_name': 'Doe'}, {'id': 3, 'first_name': 'Harshita', 'last_name': 'kumari'}, {'id': 4, 'first_name': 'Jackson', 'last_name': 'Jack'}, {'i
d': 5, 'first_name': 'Mariya', 'last_name': 'Walker'}, {'id': 6, 'first_name': 'Vishvajit', 'last_name': 'Rao'}, {'id': 7, 'first_name': 'Steve', 'last_name': 'Jobs'}, {'id': 8, 'first
_name': 'Ratan', 'last_name': 'Tata'}, {'id': 9, 'first_name': 'Elon', 'last_name': 'Musk'}, {'id': 10, 'first_name': 'Sunder', 'last_name': 'Pichai'}, {'id': 11, 'first_name': 'Mark', 'last_name': 'Zuckerburk'}]>

Convert Django QuerySet to JSON using Custom Way

As Python Developers, we should have the capability to write code from scratch to convert Django Queryset to JSON object instead of using any built-in function or predefined function.
Here, I am going to write a Python function that will capably convert Django QuerySet to JSON. This function will take QuerySet as a parameter and return a converted list of dictionaries. After that, you can simply return the converter list of dictionaries data along with application/json content type using HttpResponse.

Example: views.py


from django.http import HttpResponse
from myapp.models import People


def ConvertQuerysetToJson(qs):
    if qs == None:
        return "Please provide valid Django QuerySet"
    else:
        json_data = []
        for i in qs:
            i = i.__dict__
            i.pop("_state")
            json_data.append(i)
    return json_data


def home(request):
    data = People.objects.all()
    json_data = ConvertQuerysetToJson(data)
    return HttpResponse(json_data, content_type="application/json")
Python-Tutorial-for-Beginners-2022-1

Conclusion

So, in this article, we have seen a total of several ways to convert Django Queryset to JSON. This article is very useful especially when you are going to make APIs with the help of the Python Django framework or your work withing as an API developer.

JSON is one of the most popular data formats that travel between server and client to make transmit the data. It always stores the data in the form of key and value pairs.

If you like this article, please share and keep visiting for further Python Django interesting tutorials.

Reference:- Django Official

Thanks for your valuable time…. πŸ™πŸ™πŸ§‘β€πŸ’»πŸ§‘β€πŸ’»

Previous Article

Related Posts