周晓楠

导航

 

这是我的model里面的表

复制代码
1 class User(models.Model):
2     username = models.CharField(max_length=32,verbose_name='用户名')
3     age = models.IntegerField(verbose_name='年龄',null=True)
4     home = models.CharField(max_length=32,verbose_name='家乡')
5 
6     class Meta:
7         db_table = 'user'
复制代码

普通序列化

复制代码
from rest_framework import serializers   #倒入rest_framework里面的serializers


class UserSer(serializers.Serializer):
    username = serializers.CharField(max_length=32)   #把每个字段添入其中
    age = serializers.IntegerField(allow_null=True)  #年龄可以为null
    home = serializers.CharField(max_length=32)

######################################################################
查到的数据
{
        "username": "孔加贝月月",
        "age": 19,
        "home": "河南"
    },
    {
        "username": "尼大爷",
        "age": 20,
        "home": "河北"
    },
    {
        "username": "尼大娘",
        "age": 21,
        "home": "湖北"
    },
    {
        "username": "尼你妹",
        "age": 20,
        "home": "湖南"
    },
    {
        "username": "孔大爷",
        "age": 100,
        "home": "你心里"
    }
复制代码

添加数据的序列化

复制代码
from rest_framework import serializers

from app01.models import User
#还是刚刚那个序列化只不过是添加了一些代码
class UserSer(serializers.Serializer):
    username = serializers.CharField(max_length=32)
    age = serializers.IntegerField(allow_null=True)
    home = serializers.CharField(max_length=32)
    
    #序列化添加数据
    def create(self,validated_data):
        return User.objects.create(**validated_data)

##相对应views里面的代码
def post(self,request):
data = request.data
user = UserSer(data=data)
try:
user.is_valid()
user.save()
return Response('成功')
except Exception:
print('序列化加入未成功')
return Response('失败')
复制代码

修改的序列化

复制代码
class UserSer(serializers.Serializer):
    username = serializers.CharField(max_length=32)
    age = serializers.IntegerField(allow_null=True)
    home = serializers.CharField(max_length=32)

    #序列化添加数据
    def create(self,validated_data):
        return User.objects.create(**validated_data)

   #这里开始是修改的序列化
    def update(self, instance, validated_data):
        instance.username = validated_data.get('username',instance.username)   #把他的每个字段都写入其中进行修改
        instance.age = validated_data.get('age',instance.age)
        instance.home = validated_data.get('home',instance.home)

        instance.save()    #提交 修改
        return instance

#修改相对应的views里的代码
def put(self,request):
    data = request.data

user = User.objects.filter(id=data.get('id')).first()
update_user = UserSer(user,data=data)

try:
update_user.is_valid()
update_user.save()
return Response('成功')
except Exception as e:
print(e)
return Response('失败')
复制代码
posted on 2020-10-28 14:53  周晓楠  阅读(67)  评论(0编辑  收藏  举报