Django框架
【一】序列化组件
1)使用案例
- 在前端获取到后端用户表里面的所有数据,并且格式是列表套字典
# 创建模型表
class User(models.Model):
username = models.CharField(max_length=32, verbose_name="姓名")
age = models.IntegerField(verbose_name="年龄")
2)基于JsonResponse序列化数据
# 后端
def ab_ser(request):
user_queryset = models.User.objects.all()
# 返回数据格式:[{},{},,{},{},{},{}]
user_list = []
for user in user_queryset:
tmp = {
'username': user.username,
'password': user.age,
'gender': user.get_gender_display(),
}
user_list.append(tmp)
return JsonResponse(user_list, safe=False)
# return render(request, 'ab_ser.html', locals())
# 前端
<body>
{% for user_obj in user_queryset %}
<p>{{ user_obj.name }}</p>
{% endfor %}
</body>
# 数据展示
[
{"username": "dream", "password": 18, "gender": "male"},
{"username": "meng", "password": 28, "gender": "female"},
{"username": "hope", "password": 38, "gender": "others"}
]
3)基于Django自带的serializers组件
# 后端
from django.core import serializers
def ab_ser(request):
user_queryset = models.User.objects.all()
res = serializers.serialize('json', user_queryset)
'''
serializers 模块内部会帮我们将数据全部变成JSON格式的字符串,并且内部非常的全面
'''
return HttpResponse(res)
# 数据展示
[
{"model": "app01.user", "pk": 1, "fields": {"username": "dream", "age": 18, "gender": 1}},
{"model": "app01.user", "pk": 2, "fields": {"username": "meng", "age": 28, "gender": 2}},
{"model": "app01.user", "pk": 3, "fields": {"username": "hope", "age": 38, "gender": 3}}
]
【二】批量插入
def get_book_bulk(request):
# 批量插入
boo_list = []
for i in range(1000):
book_obj = models.Book.objects.create(title=f'第{i}本书')
boo_list.append(book_obj)
# 批量插入数据
models.Book.objects.bulk_create(boo_list)
return render(request, 'books.html', locals())
标签:username,models,gender,57,list,Django,queryset,user,序列化
From: https://www.cnblogs.com/Mist-/p/18280448