不使用 drf 来实现django 的 api 接口 json序列化
from django.shortcuts import render
from django.views.generic.base import View
from users.models import UserProfile
# Create your views here.
# 通用类型
class GoodsView(View):
def get(self, request):
goods = UserProfile.objects.all()
good_list = []
# for good in goods:
# good_dict = {}
# good_dict["name"] = good.username
# good_dict["email"] = good.email
# good_list.append(good_dict)
# model_to_dict 直接转为dict 不用每个字段都去填写
## 同时有个问题 就是 time 和 image 无法正常序列化
from django.forms.models import model_to_dict
for good in goods:
good_dict = model_to_dict(good)
good_list.append(good_dict)
# from django.http import HttpResponse
# import json
# return HttpResponse(json.dumps(good_list), content_type="application/json")
# 这样就是序列化 时间和图片
from django.core import serializers
import json
json_data = serializers.serialize("json",goods)
json_data = json.loads(json_data)
from django.http import HttpResponse,JsonResponse
import json
# return HttpResponse(json.dumps(json_data), content_type="application/json")
return JsonResponse(json_data,safe=False)
原文地址:https://www.cnblogs.com/libaibuaidufu/p/10164069.html
时间: 2024-10-12 21:48:41