django serializer小结(一)

1、模型。

from django.contrib.auth.hashers import check_password
from django.db import models


# Create your models here.
class User(models.Model):
    name = models.CharField(max_length=128, verbose_name='姓名')
    mobile = models.CharField(max_length=11, unique=True, verbose_name="手機號")
    pwd = models.CharField(max_length=128, verbose_name='密码')

    class Meta:
        db_table = 'users'
        verbose_name = "用戶信息"

    def __str__(self):
        return self.name


    def verify_password(self, pwd):
        return check_password(pwd, self.employee_pwd)

2、路由。

url(r'^Reginster/$', views.ReginsterView.as_view({'post': 'create'})),

3、序列化。

import re
from django.contrib.auth.hashers import make_password
from rest_framework import serializers
from api import models


class RegisterSerializer(serializers.ModelSerializer):
    pwd2=serializers.CharField(max_length=11,write_only=True)

    class Meta:
        model = models.User
        fields = '__all__'   # 输出所有字段
        # exclude = ['pwd']   # 过滤密码字段

    def validate_mobile(self, value):
        if not re.match(r"^1[3-9]\d{9}", value):
            raise serializers.ValidationError("手機號碼格式不正確!")
        return value


    def validate(self, attrs):
        if attrs['pwd'] != attrs['pwd2']:
            raise serializers.ValidationError("兩次密碼輸入不一致!")
        if not attrs['pwd'].startswith('pbkdf2_'):
            attrs['pwd'] = make_password(attrs['pwd'])
        del attrs["pwd2"]   # 移除不在model但是需要校验的字段
        return attrs

4、视图。

from django.shortcuts import render,HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
# Create your views here.
from api.ser import RegisterSerializer

class ReginsterView(ModelViewSet):
    serializer_class=RegisterSerializer

    def post(self, request, *args, **kwargs):
        ser=self.serializer_class(data=request.data) 
        ser.is_valid(raise_exception=True)
        try:
            self.perform_create(ser)
            return Response({'code': 200, 'msg': '新增成功!'})
        except:
            return Response({'code': 400, 'msg': '新增失败!'})

5、结果。

django serializer小结(一)_第1张图片

6、extra,添加额外的输出。


class RegisterSerializer(serializers.ModelSerializer):
    days_since_joined=serializers.SerializerMethodField()
    
    # 方法写法:get_ + 字段
    def get_days_since_joined(self, obj):
        # obj指这个model的对象
        return '%s-24'%obj.name

 参考:https://www.jianshu.com/p/e5c30bd9919e

你可能感兴趣的:(Django)