感谢alex和武沛齐老师
rest_framework中的序列化表示
from rest_framework import serializers
class RoleSerializer(serializers.Serializer):
id = serializers.IntegerField()
title = serializers.CharField()
class RolesView(APIView):
def get(self, request, *args, **kwargs):
#方式1
#roles = models.Role.objects.all().values('id','title')
#roles = list(roles)
#ret = json.dumps(roles, ensure_ascii=False)
#方式2 对queryset的格式进行序列化
roles = models.Role.objects.all()
ser = RolesSerializer(instance=roles, many=True)
ret = json.dumps(ser.data, ensure_ascii=False)
return HttpResponse(ret)
#方式2 单个对象
roles = models.Role.objects.all().first()
ser = RolesSerializer(instance=roles, many=False)
#ser.data 已经是完成序列化的结果了
ret = json.dumps(ser.data, ensure_ascii=False)
return HttpResponse(ret)
def func(arg):
if callable(arg):
print(arg())
else:
print(arg)
func(123)
func(lambda:"666")
序列化
部分总结:
1.写类
继承下面两种
class RolesSerializer(serializers.Serializer):
id = serializers.IntegerFiled()
title = serializers.CharField()
class UserInfoSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserInfo
#fileds = "__all__"
fields = ['id', 'username', 'password']
2.字段
a. title = serializers.CharField(source = 'group.title')
b. title = serializers.SerializerMethodField()
class UserInfoSerializer(serializers.ModelSerializer):
rls = serializers.SerializerMethodField() #自定义显示
class Meta:
model = models.UserInfo
fields = ['id', 'username', 'password', 'rls',]
#自定义方法
def get_rls(self, row)
role_obj_list = row.roles.all()
ret = []
for item in role_obj_list:
ret.append({'id':item.id, 'title':item.title})
return ret
c.自定义类 不过用得少
视图函数中
from cmdb import models
from rest_framework import serializers
#方式1 序列化
# class UserInfoSerializer(serializers.Serializer):
# username = serializers.CharField()
# password = serializers.CharField()
# xxxx = serializers.CharField(source="user_type") #source表示对应数据库的某个字段 此时就可以改变变量了 row.get_user_type_display 不可执行
# oooo = serializers.CharField(source="get_user_type_display") #对choices数据进行获取中文 可执行
#
# group = serializers.CharField(source="group.title") #foreignkey 进行.操作 跨表
# #rls = serializers.CharField(source='roles.all')
# #如果是单个表和foreignkey可以通过source去指定 不能指定manytomany
#
# rls = serializers.SerializerMethodField()#自定义显示
# def get_rls(self, row):
# role_obj_list = row.roles.all()
# ret = []
# for item in role_obj_list:
# ret.append({'id':item.id,"title":item.title})
# return ret
#方式2 #地址 www.cnblogs.com/wupeiqi/articles/7805382.html
#方式2可以与方式1中的数据混合着使用
class UserInfoSerializer(serializers.ModelSerializer):
oooo = serializers.CharField(source="get_user_type_display")
rls = serializers.SerializerMethodField()
group = serializers.CharField(source='group.title')
class Meta:
model = models.UserInfo
#fields = "__all__" #这一步已经可以完成基本的所有数据的显示
fields = ['id','username','password','oooo','rls','group']
def get_rls(self, row):
role_obj_list = row.roles.all()
ret = []
for item in role_obj_list:
ret.append({'id':item.id, 'title':item.title})
return ret
import json
class UserInfoView(APIView):
def get(self, request, *args, **kwargs):
users = models.UserInfo.objects.all()
ser = UserInfoSerializer(instance=users,many=True)
print(ser.data)
ret = json.dumps(ser.data, ensure_ascii=False)
return HttpResponse(ret)
urls.py中
from django.conf.urls import url,include
from cmdb import views
urlpatterns = [
url(r'^(?P<version>[v1|v2]+)/userinfo/$',views.UserInfoView.as_view()),
]
models.py中
from django.db import models
# Create your models here.
class UserGroup(models.Model):
title = models.CharField(max_length=32)
class UserInfo(models.Model):
user_type_choices = (
(1,'普通用户'),
(2,'VIP'),
(3,'SVIP'),
)
user_type = models.IntegerField(choices=user_type_choices)
group = models.ForeignKey(to="UserGroup", on_delete=models.CASCADE)
username = models.CharField(max_length=32, unique=True)
password = models.CharField(max_length=64)
roles = models.ManyToManyField(to="Role")
class UserToken(models.Model):
user = models.OneToOneField(to="UserInfo", on_delete=models.CASCADE)
token = models.CharField(max_length=64)
class Role(models.Model):
title = models.CharField(max_length=32)