5.1.通过django的view实现api

基础实现

通过django的view实现商品列表页

import json

from django.http import HttpResponse
from django.views.generic.base import View

from goods.models import Goods


class GoodsListView(View):
    def get(self, request):
        json_list = []
        goods = Goods.objects.all()[:10]
        for good in goods:
            json_dict = {}
            json_dict['name'] = good.name
            json_dict['category'] = good.category.name
            json_dict['market_price'] = good.market_price
            json_list.append(json_dict)

        return HttpResponse(json.dumps(json_list), content_type='application/json')

使用model_to_dict快速转换model为dict

import json

from django.http import HttpResponse
from django.shortcuts import render
from django.views.generic.base import View

from goods.models import Goods


class GoodsListView(View):
    def get(self, request):
        json_list = []
        goods = Goods.objects.all()[:10]

        from django.forms.models import model_to_dict
        for good in goods:
            json_dict = model_to_dict(good)
            json_list.append(json_dict)

        return HttpResponse(json.dumps(json_list), content_type='application/json')

存在问题:json库无法转换非原生python类型

报错TypeError: Object of type ImageFieldFile is not JSON serializable

使用serializers序列化对象为json

import json

from django.http import HttpResponse
from django.views.generic.base import View

from goods.models import Goods


class GoodsListView(View):
    def get(self, request):
        json_list = []
        goods = Goods.objects.all()[:10]

        from django.forms.models import model_to_dict
        for good in goods:
            json_dict = model_to_dict(good)
            json_list.append(json_dict)

        from django.core import serializers
        json_data = serializers.serialize('json', goods)

        return HttpResponse(json_data, content_type='application/json')

使用JsonResponse简化HttpResponse

import json

from django.http import HttpResponse
from django.views.generic.base import View

from goods.models import Goods


class GoodsListView(View):
    def get(self, request):
        json_list = []
        goods = Goods.objects.all()[:10]

        from django.forms.models import model_to_dict
        for good in goods:
            json_dict = model_to_dict(good)
            json_list.append(json_dict)

        from django.core import serializers
        json_data = serializers.serialize('json', goods)
        json_data = json.loads(json_data)

        from django.http import JsonResponse
        return JsonResponse(json_data, safe=False)

结果

[
  {
    "model": "goods.goods",
    "pk": 1,
    "fields": {
      "category": 4,
      "name": "西班牙猪肉",
      "market_price": 0.0,
      ...
    }
  },
  ...
]

存在问题:结果格式不符合一般使用习惯,比如:主键在外,model、fields等多余字段

Last updated

Was this helpful?