django的serializer序列化model

Object of type ImageFieldFile is not JSON serializable

实现一

from django.views.generic.base import View
from django.http import HttpResponse
from goods.models import Goods
from django.core import serializers

class GoodsListView(View):
    def get(self, request):
        '''
        通过django的view实现商品列表页
        :param request:
        :return:
        '''
        goods = Goods.objects.all()[:10]

        json_data = serializers.serialize('json', goods)
        return HttpResponse(json_data, content_type='application/json')

实现二

from django.views.generic.base import View
from django.http import JsonResponse
from goods.models import Goods
from django.core import serializers
import json

class GoodsListView(View):
    def get(self, request):
        '''
        通过django的view实现商品列表页
        :param request:
        :return:
        '''
        goods = Goods.objects.all()[:10]

        json_data = serializers.serialize('json', goods)
        json_data = json.loads(json_data)
        return JsonResponse(json_data, safe=False)

part 2老男孩Django序列化

  1. serialize只能对queryset进行序列化
  2. list()
    user_list = UserInfo.objects.values('email')
    user_list = list(user_list) #将queryset变成list
    return HttpResponse(dumps(user_list))

你可能感兴趣的:(天天生鲜)