【补充】Django自带的序列化组件
【11.0补充】Django自带的序列化组件
【一】准备数据
from django.db import models
# Create your models here.
class User(models.Model):
username = models.CharField(max_length=32, verbose_name="姓名")
age = models.IntegerField(verbose_name="年龄")
gender_choices = (
(1, 'male'),
(2, 'female'),
(3, 'others')
)
gender = models.IntegerField(choices=gender_choices, verbose_name="性别")
【二】需求
- 在前端获取到后端用户表里面的所有数据,并且格式是列表套字典
【1.0】简单版本
- 后端
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"}
]
【2.0】升级版
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}}
]
本文来自博客园,作者:Chimengmeng,转载请注明原文链接:https://www.cnblogs.com/dream-ze/p/17559622.html