1.unique_together 序列化器层:
rom rest_framework.validators import UniqueValidator,UniqueTogetherValidator
class UserSerializer(serializers.ModelSerializer):
# style表示前台输入是密文,write_only表示序列化时不会序列化该字段
password = serializers.CharField(write_only=True, max_length=256)
uuid = serializers.UUIDField(read_only=True)
class Meta:
model = User
fields = ('uuid', 'username', 'password', 'mobile', 'email')
extra_kwargs = {
"password": {"write_only": True}
}
validators = [
UniqueTogetherValidator(
queryset=User.objects.all(),
fields=['username', 'mobile']
)
]
# 创建用户时更新密码为密文
def create(self, validated_data):
user = super().create(validated_data)
user.set_password(validated_data['password'])
user.save()
return user
# 更新用户时更新密码为密文
def update(self, instance, validated_data):
user = super().update(instance, validated_data)
if 'password' in validated_data.keys():
user.set_password(validated_data['password'])
user.save()
return user
# 重写to_representation方法,自定义响应中的json数据
def to_representation(self, instance):
ret = super().to_representation(instance)
ret['uuid'] = ret['uuid'].replace('-', '')
return ret
模型层:
class User(models.Model):
uuid = models.UUIDField(default=UUIDTools.uuid4_hex)
username = models.CharField(max_length=32, unique=True)
password = models.CharField(max_length=256)
mobile = models.CharField(max_length=11, blank=True, unique=True) # 可选
email = models.EmailField(max_length=64, blank=True, unique=True)
# role = models.ManyToManyField(to=Roles, related_name='role')
def set_password(self, password):
self.password = make_password(password)
return None
def check_pwd(self, password):
# password 入参原始密码
db_pwd = self.password
return check_password(password, db_pwd)
class Meta:
db_table = "tbl_user"
verbose_name = 'user信息表'
unique_together = (
('username', 'mobile')
)
二。unique检验:
class SerializerTestCase(serializers.ModelSerializer):
id = serializers.IntegerField(read_only=True)
case_name = serializers.CharField(max_length=50, required=True,
validators=[UniqueValidator(queryset=TestCase.objects.all())])
project_id = serializers.IntegerField(required=True,min_value=1)
project_name = serializers.SerializerMethodField()
method = serializers.CharField(max_length=10, required=True)
url = serializers.CharField(max_length=500, required=True)
params = serializers.CharField(max_length=500, allow_blank=True, allow_null=True)
headers = serializers.JSONField()
mine_type = serializers.CharField(max_length=5, required=True)
body = serializers.JSONField()
模型:
class TestCase(models.Model):
case_name = models.CharField(max_length=50, null=False, unique=True)
project_id =models.IntegerField(null=False)
method = models.CharField(max_length=10, null=False)
url = models.CharField(max_length=500, null=False)
params = models.CharField(max_length=500, null=True)