Django自带的序列化组件

Django自带的序列化组件(为drf做铺垫)

(drf:django rest framework)

#在前端获取到,后端用户表里所有的数据,并且是列表套字典的格式
# views.py

from django.http import JsonResponse

def ab_ser(request):
    user_queryset = models.User.objects.all()
    user_list = []
    for user_obj in user_queryset:
        tmp = {
            'pk': user_obj.pk,
            'username': user_obj.username,
            'age': user_obj.age,
            'gender': user_obj.get_gender_display()
        }
        user_list.append(tmp)
    return JsonResponse(user_list, safe=False)

前端显示结果:

image-20221103175900052

"""
[
  {"pk": 1,"username": "zhao","age": 19,"gender": "male"},
  {"pk": 2,"username": "lisi","age": 20,"gender": "female"},
  {"pk": 3,"username": "wangwu","age": 18,"gender": "others"},
  {"pk": 4,"username": "tony","age": 22,"gender": 4}
]

"""

前后端分离项目
	作为后端开发,只需要写代码将数据返回
    能够序列化返回给前端即可
    	再写一个接口文档,告诉前端每个字段代表的意思即可

借助于内置序列化模块serializers

from django.core import serializers


def ab_ser(request):
    user_queryset = models.User.objects.all()
    # user_list = []
    # for user_obj in user_queryset:
    #     tmp = {
    #         'pk': user_obj.pk,
    #         'username': user_obj.username,
    #         'age': user_obj.age,
    #         'gender': user_obj.get_gender_display()
    #     }
    #     user_list.append(tmp)
    # return JsonResponse(user_list, safe=False)

    # 序列化
    res = serializers.serialize('json', user_queryset)  # 自动将数据变成json格式的数据,并且内部非常的全面
    return HttpResponse(res)

效果:

[
  {
    "model": "app01.user",
    "pk": 1,
    "fields": {"username": "zhao","age": 19,"gender": 1}
  },
  {
    "model": "app01.user",
    "pk": 2,
    "fields": {"username": "lisi","age": 20,"gender": 2}
  },
  {
    "model": "app01.user",
    "pk": 3,
    "fields": {"username": "wangwu","age": 18,"gender": 3}
  },
  {
    "model": "app01.user",
    "pk": 4,
    "fields": {"username": "tony","age": 22,"gender": 4}
  }
]

#后端开发写接口就是利用序列化组件渲染数据,然后写一个接口文档,

image-20221104205336198

posted @ 2022-12-12 16:44  ExpiredSaury  阅读(23)  评论(0编辑  收藏  举报