Django: How to Convert Models object to JSON

1. When the models object uses “all()”:

from django.core import serializers 


data_set = models.Areas.objects.all()
res = serializers.serialize("json",data_set)

2. When the models object is a single value “get()”:

from django.forms.models import model_to_dict

obj = models.Areas.objects.get(id=value)
res = model_to_dict(obj)

3. The models object uses values or values_ List:

res={"status":True,"data":""}
obj = models.Areas.objects.values("id","name")
obj_list = list(obj)  #Need to convert to a list, otherwise it will report an error
res["data"] = obj_list
return JsonResponse(res,safe=False)

Similar Posts: