Django converts queryset (serialization of model instance) to a dictionary (json) method

created at 07-17-2021 views: 1

There are many documents on how to serialize a model query set, but how to serialize the fields of a model instance to JSON?

method 1: use django's own method serializers

from django.core import serializers

obj = SomeModel.objects.first()

serialized_obj = serializers.serialize('json', [ obj, ])

serialized_obj = serializers.serialize('python', [ obj, ])

difference between json and python format

json format will return the result as str, while python will return the result list or OrderedDict

method 2: use model_to_dict

from django.forms.models import model_to_dict
from django.http import JsonResponse

obj = SomeModel.objects.first()
model_to_dict(obj )

method 3: use json.dumps()

from django.forms import model_to_dict
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import Model

class ExtendedEncoder(DjangoJSONEncoder):

    def default(self, o):

        if isinstance(o, Model):
            return model_to_dict(o)

        return super().default(o) 

json.dumps(data, cls=ExtendedEncoder)
Please log in to leave a comment.