Progger Progger - 1 year ago 111
JSON Question

Return proper JSON from Django JsonResponse

My Model:

class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
phone = models.CharField(max_length=20)
email = models.EmailField()

My View:

def users(request):
people = Person.objects.all()
data = serializers.serialize('json', people)
return JsonResponse(data, safe=False)

All I want back is the data in JSON format. What I'm getting back is this:

"[{\"model\": \"myapp.person\", \"pk\": 1, \"fields\": {\"first_name\": \"ahmet\", \"last_name\": \"arsan\", \"phone\": \"xxx-xxx-xxxx\", \"email\": \"\"}}]"

While technically that is valid JSON, there are 2 problems (for me) with this response:

  1. I don't want those double quotes escaped.

  2. I don't need the model name (myapp.person).

I don't know if/what I'm doing wrong, but it seems like something is off here. Perhaps my query should be returning a dict but I don't know how to get it to do that. I am using Django 1.10.1, Python 3.4.

Answer Source

I am assuming you are asking this question for an API response. I would suggest using Rest Framework for that as it makes things very easy. You can select your own fields by writing your own serializers for the model.

from rest_framework import serializers

class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields = ('first_name', 'last_name', 'phone', 'email')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download