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

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

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

使用serializers序列化对象为json

使用JsonResponse简化HttpResponse

结果

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

Last updated

Was this helpful?