3
April 18, 2016  
In Articles by Iunary

Nowadays JSON is becoming very popular for easy and fast data formatting, it is being used by most APIs over the web services.

In this post we are going to talk about Django objects serialization into JSON and it will be a useful idea of making a read-only RESTFUL API or when you axajify a web application.

Creating a Django app

First of all let's create a django app named news and adding it to our INSTALLED_APPS in django settings:

./manage.py startapp news

Then

INSTALLED_APPS = (
   ....,
   news,
)

For our Django model we are going to use the following code:

from django.db import models
class Thread(models.Model):
    title = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(max_length=250)
    link = models.URLField()
    created = models.DateTimeField(auto_now_add=True)

Now it's time to use the makemigrations and migrate command to migrate our the database.

./manage.py makemigrations

./manage.py migrate

Serialization demo

Let's use the serializers class provided by django serialization framework to serialize the Thread objects into a JSON data by using the following lines of code.

from django.core import serializers
from news.models import Thread

threads = Thread.objects.all()
json_data = serializers.serialize('json', threads)

And we will the the following result:

[{
    "fields": {
        "title": "Hello World - Machine Learning Recipes #1",
        "created": "2016-04-16T22:13:20.349Z",
        "link": "https://www.youtube.com/watch?v=cKxRvEZd3Mw",
        "slug": "hello-world-machine-learning-recipes-1"
    },
    "model": "news.thread",
    "pk": 1
}, {
    "fields": {
        "title": "What\\u2019s a deque?",
        "created": "2016-04-16T17:02:08.777Z",
        "link": "http://www.blog.pythonlibrary.org/2016/04/14/python-201-whats-a-deque/",
        "slug": "whats-a-deque"
    },
    "model": "news.thread",
    "pk": 2
}]

As you see it's so simple and easy to get your django model objects into json and we we are going to see how to expose it to the web.

There are many ways to return JSON over an http request using django and i will mention one of them.

Using HttpResponse with json content type

from django.http import HttpResponse
from django.core import serializers
from news.models import Thread
def threads(request):
    threads = Thread.objects.all()
    return HttpResponse(serializers.serialize('json', threads), content_type="application/json")

Hopefully this simple post will be useful for you.


0 Comments

There are currently no comments. You can be first!

Sign in