如何让django返回json数据人类可读

时间:2016-07-22 09:17:22

标签: json django api

每一个,我都有

  

models.py

.......

class ProductsTbl(models.Model):
    model_number = models.CharField(
        max_length=255,
        blank=True,
        unique=True,
        error_messages={
            'unique': "這 model number 已經被註冊了 ."
        }
    )
    name = models.CharField(max_length=255, blank=True, null=True)
    material = models.CharField(max_length=255, blank=True, null=True)
    color = models.CharField(max_length=255, blank=True, null=True)
    feature = models.TextField(blank=True, null=True)
    created = models.DateTimeField(editable=False)
    modified = models.DateTimeField(auto_now=True)
    release = models.DateTimeField(blank=True, null=True)
    twtime = models.DateTimeField(blank=True, null=True)
    hktime = models.DateTimeField(blank=True, null=True)
    shtime = models.DateTimeField(blank=True, null=True)
    jptime = models.DateTimeField(blank=True, null=True)
    suggest = models.TextField(blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    cataloggroup = models.ManyToManyField(CatalogGroup)
    place = models.ManyToManyField(Place)
    scale = models.ManyToManyField(Scale)
    slug = models.SlugField(unique=True)
    user = models.ForeignKey(User, blank=True, null=True)
    useredit = models.CharField(max_length=32, blank=True, null=True)
    image = models.ImageField(upload_to=get_imagep_Product, blank=True)

    def __unicode__(self):
        return self.name

    def save(self, *args, **kwargs):
        ''' On save, update timestamps '''

        if not self.id:
            self.created = timezone.now()

        return super(ProductsTbl, self).save(*args, **kwargs)

并且,我正在为api返回json数据,这里是

  

views.py

from django.http import JsonResponse
from django.core import serializers
.....
def get_index(request):

    obj = ProductsTbl.objects.order_by('-created')
    data = serializers.serialize("json", obj)

    return JsonResponse(data,safe=False)

然而,我得到了像这样的

的json数据

enter image description here

我的问题是如何让django返回json数据,人类可以像这样读取

enter image description here

感谢任何回复我的人

2 个答案:

答案 0 :(得分:0)

用户DRF api_view

from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view()
def get_index(request):

    obj = ProductsTbl.objects.order_by('-created')
    data = serializers.serialize("json", obj)

    return Response(data)

答案 1 :(得分:0)

您可以按照以下方式更改views.py:

from django.http import JsonResponse
from django.core import serializers
.....
def get_index(request):

    obj = ProductsTbl.objects.order_by('-created')
    data = self.stdout.write(serializers.serialize("json",
                                        obj,
                                        indent=2))

    return HttpResponse(json.dumps(data),content_type="application/json")

或者看this你会有所了解。