django 查询数据库得到的结果序列化成json字符串

# -*- coding: utf-8 -*-


class GoodsListView(View):

    def get(self, request):

    1、方法一:(for in 循环遍历model)
    	# 定义一个空列表
    	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_dict["add_time"] = good.add_time
            json_list.append(json_dict)
        from django.http import HttpResponse
        import json
        # 序列化成json字符串,返给前台
        return HttpResponse(json.dumps(json_list), content_type="application/json")

    2、方法二:(django自带的serializers序列化model)(推荐使用此方法)
        import json 
        from django.core import serializers
        json_data = serializers.serialize('json', goods)
        json_data = json.loads(json_data)
        from django.http import HttpResponse, JsonResponse
        return JsonResponse(json_data, safe=False)

    3、方法三:(model_to_dict方法)
        from django.forms.models import model_to_dict
        for good in goods:
            json_dict = model_to_dict(good)
            json_list.append(json_dict)

猜你喜欢

转载自blog.csdn.net/qq_33867131/article/details/80910178