Django之序列化组件

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

数据准备

models.py

  1. class User(models.Model):
  2. name = models.CharField(max_length=32)
  3. age = models.IntegerField()
  4. gender_choice = (
  5. (1, 'male'),
  6. (2, 'female'),
  7. (3, 'other'),
  8. )
  9. gender = models.IntegerField(choices=gender_choice)
  10. addr = models.CharField(max_length=32)

Django之序列化组件 - 图1

view.py

  1. from django.shortcuts import render, HttpResponse, redirect
  2. from app01 import models
  3. from django.http import JsonResponse
  4. from django.core import serializers
  5. def index(request):
  6. # data_list = [] # [{},{},{}]
  7. # user_queryset = models.User.objects.all()
  8. #
  9. # for user_obj in user_queryset:
  10. # data_list.append({
  11. # 'pk': user_obj.pk,
  12. # 'name': user_obj.name,
  13. # 'age': user_obj.age,
  14. # 'gender': user_obj.get_gender_display(),
  15. # 'addr': user_obj.addr
  16. # })
  17. user_queryset = models.User.objects.all()
  18. res = serializers.serialize('json', user_queryset)
  19. return HttpResponse(res)

批量数据操作

  1. def index(request):
  2. """批量插入"""
  3. book_list = []
  4. for i in range(10000):
  5. # 先用类产生一个对象
  6. source_book_obj = models.Book(title=f'第{i}本书')
  7. # 将对象追加到列表中
  8. book_list.append(source_book_obj)
  9. models.Book.objects.bulk_create(book_list) # 批量插入
  10. book_queryset = models.Book.objects.all()
  11. return render(request, 'index.html', locals())