django 조회 데이터베이스에서 얻은 결과를 json 문자열로 서열화

1246 단어 django
# -*- 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)

좋은 웹페이지 즐겨찾기