【Vue+DRF生鲜电商】05.商品列表序列化普通方法

2019-04-21  本文已影响0人  吾星喵

欢迎访问我的博客专题

源码可访问 Github 查看

普通视图序列化

JSONView

访问 https://github.com/gildas-lormeau/JSONView-for-Chrome 下载

选择插件目录 JSONView-for-Chrome-master\WebContent

image.png

View实现商品列表-json

在goods应用下创建 views_base.py 文件,增加一下内容

from django.views.generic.base import View
from django.views.generic import ListView
from goods.models import Goods


class GoodsListView(View):
    def get(self, request):
        """
        通过Django的View获取商品列表页
        :param request:
        :return:
        """
        json_list = list()
        all_goods = Goods.objects.all()[:5]
        print(all_goods)
        for goods in all_goods:
            json_dict = dict()
            json_dict['name'] = goods.name
            json_dict['category'] = goods.category.name
            json_dict['shop_price'] = goods.shop_price
            json_list.append(json_dict)

        from django.http import HttpResponse
        import json
        return HttpResponse(json.dumps(json_list), content_type='application/json')

修改项目配置文件夹的主 urls.py ,增加该视图的url

from goods.views_base import GoodsListView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api-auth/', include('rest_framework.urls')),
    path('ckeditor/', include('ckeditor_uploader.urls')),  # 配置富文本编辑器url
    path('goods/', GoodsListView.as_view(), name='goods_list')
]

访问 http://127.0.0.1:8000/goods/

image.png

但这种方式需要将每个字段加到json中去,如果遇到DateTimeField字段,是不能序列化的。

View实现商品列表-model_to_dict

解决字段多的情况,在我们的模型中,如果字段多,像上面的方法,是非常麻烦的。

from django.views.generic.base import View
from django.views.generic import ListView
from goods.models import Goods


class GoodsListView(View):
    def get(self, request):
        """
        通过Django的View获取商品列表页
        :param request:
        :return:
        """
        json_list = list()
        all_goods = Goods.objects.all()[:5]
        # print(all_goods)
        # for goods in all_goods:
        #     json_dict = dict()
        #     json_dict['name'] = goods.name
        #     json_dict['category'] = goods.category.name
        #     json_dict['shop_price'] = goods.shop_price
        #     json_list.append(json_dict)

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

        from django.http import HttpResponse
        import json
        return HttpResponse(json.dumps(json_list), content_type='application/json')

以上方式虽然能获取所有字段,但对于ImageFieldDateTimeField仍然是不支持的

实现商品列表-serializers

class GoodsListView(View):
    def get(self, request):
        """
        通过Django的View获取商品列表页
        :param request:
        :return:
        """
        json_list = list()
        all_goods = Goods.objects.all()[:5]
        # print(all_goods)
        # for goods in all_goods:
        #     json_dict = dict()
        #     json_dict['name'] = goods.name
        #     json_dict['category'] = goods.category.name
        #     json_dict['shop_price'] = goods.shop_price
        #     json_list.append(json_dict)

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

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

        from django.http import HttpResponse, JsonResponse
        import json
        return HttpResponse(json_data, content_type='application/json')
image.png

再使用JsonResponse

class GoodsListView(View):
    def get(self, request):
        """
        通过Django的View获取商品列表页
        :param request:
        :return:
        """
        json_list = list()
        all_goods = Goods.objects.all()[:5]
        # print(all_goods)
        # for goods in all_goods:
        #     json_dict = dict()
        #     json_dict['name'] = goods.name
        #     json_dict['category'] = goods.category.name
        #     json_dict['shop_price'] = goods.shop_price
        #     json_list.append(json_dict)

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

        from django.core import serializers
        json_data = serializers.serialize('json', all_goods)  # 序列化

        from django.http import HttpResponse, JsonResponse
        import json
        # return HttpResponse(json_data, content_type='application/json')
        json_data = json.loads(json_data)  # 转换为数组
        return JsonResponse(json_data)

会出现错误:TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False.

可以进行如下配置

return JsonResponse(json_data)
# 修改为
return JsonResponse(json_data, safe=False)

同样也可以正常显示json数据

使用serializer缺点

image.png
上一篇 下一篇

猜你喜欢

热点阅读