5.1.通过django的view实现api
基础实现
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
使用serializers序列化对象为json
使用JsonResponse简化HttpResponse
结果
Last updated