序列化组件

当前后端分离后ORM产生的QuerySet无法直接被前端识别,而是需要json格式数据

数据准备

models.py

class User(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    gender_choice = (
        (1, 'male'),
        (2, 'female'),
        (3, 'other'),
    )
    gender = models.IntegerField(choices=gender_choice)
    addr = models.CharField(max_length=32)

view.py

from django.shortcuts import render, HttpResponse, redirect
from app01 import models
from django.http import JsonResponse
from django.core import serializers


def index(request):
    #     data_list = []  # [{},{},{}]
    #     user_queryset = models.User.objects.all()
    #
    #     for user_obj in user_queryset:
    #         data_list.append({
    #             'pk': user_obj.pk,
    #             'name': user_obj.name,
    #             'age': user_obj.age,
    #             'gender': user_obj.get_gender_display(),
    #             'addr': user_obj.addr
    #         })
  
    user_queryset = models.User.objects.all()
    res = serializers.serialize('json', user_queryset)
    return HttpResponse(res)

批量数据操作

def index(request):
    """批量插入"""
    book_list = []
    for i in range(10000):
        # 先用类产生一个对象
        source_book_obj = models.Book(title=f'第{i}本书')
        # 将对象追加到列表中
        book_list.append(source_book_obj)
    models.Book.objects.bulk_create(book_list)  # 批量插入
    book_queryset = models.Book.objects.all()
    return render(request, 'index.html', locals())
Last modification:May 29, 2022
如果觉得我的文章对你有用,请随意赞赏