1. 利用遍历queryset集合,构造dict,然后用json.dumps()序列化成json对象
goods = Good.objects.all()
json_list = []
for good in goods:
json_dict = {}
json_dict["name"] = good.name
...
json_list.append(json_dict)
import json
json_data = json.dumps(jaon_list)
2. 利用django的model_to_dict将queryset序列化成字典
from django.forms.models import model_to_dic
goods = Good.objects.all()
json_list = []
for good in goods:
json_dict = model_to_dict(good)
json_list.append(json_dict)
3.利用Django的serialize序列化成json对象
import json
from django.core.serializers import serialize
json_data = serialize('json', goods) # str
json_data = json.loads(json_data) # 序列化成json对象
注意:第一种、二种方式不能序列化时间类型和图片类型,第三种可以