There are multiple implementations of JSONField that can be used for storing arbitary JSON data in Django models:
-
Third-party implementations
The one I am using is
jsonfield2
which is an updated fork of a popular implementation that works with Django 2+. Following example assumes this package being used.
Let's assume a model:
from jsonfield import JSONField
class Product(models.Model):
title = models.CharField(max_length=255)
images = JSONField()
and a serializer for the same:
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ('title', 'images',)
By default, Django Rest Framework will return images as JSON data quoted as string. What that means is if the field images
had list of images like ['image1.png', 'image2.png']
, the output of the API would have been as follows:
{
title: "Some title",
images: "['image1.png', 'image2.png"]"
}
Notice how images
is returned as string instead of as an array? That's because we need to specify it as JSONField
in the serializer:
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
images = serializers.JSONField()
class Meta:
model = Product
fields = ('title', 'images',)
With this in place, the API will now return:
{
title: "Some title",
images: ['image1.png', 'image2.png"]
}
which is what we had been expecting.