使用django返回数据

import json
from django.views import View
# from django.views.generic.base import View
from goods.models import goods
from django.http import HttpResponse

class GoodsListView(View):
  def get(self, request):
    json_list = []
    goods = goods.objects.all()
    for good in goods:
      json_dict = {}
      json_dict['name'] = good.name
      json_dict['category'] = good.category.name
      json_dect['market_price'] = good.market_price
      json_list.append(json.dict)
    return HttpResponse(json.dumps(json_list), content_type = 'application/json')
from goods.views import GoodsListView
from django.urls import path

urlpatterns = [
  path('goods/', GoodsListView.as_view(), name='goods'),
]

使用django原生返回json格式的数据会有一些问题,例如:在数据库中存储datetime类型的数据会无法序列化, 数据库字段太多就会很麻烦

完善models:

import json
from django.core import serializers
# from django.forms.models import model_to_dict
from django.views import View
# from django.views.generic.base import View
from goods.models import goods
from django.http import HttpResponse, JsonResponse


class GoodsListView(View):
    def get(self, request):
        # json_list = []
        goods = goods.objects.all()
        # for good in goods:
            # json_dict = model_to_dict(good)
            # json_list.append(json.dict)
        json_data = serializers.serialize('json', goods)
        json_data = json.loads(json_data)

        return JsonResponse(json_data, safe=False)

你可能感兴趣的:(使用django返回数据)