1、Model的功能
数据库操作
a、建表
表字段
表字段参数
Meta参数
b、表关系
一对一
一对多
多对多
各种表关系参数
c、表操作
基本操作
进阶操作
高级操作
其他操作
数据字段验证
full_clean()====>clean_fields()
====>clean()
full_clean函数
参数
- 参数1、exclude
- 参数2、validate_unique
调用过程:
- 调用clean_fields
- 调用clean
- 调用validate_unique
def full_clean(self, exclude=None, validate_unique=True): """ Calls clean_fields, clean, and validate_unique, on the model, and raises a ``ValidationError`` for any errors that occurred. 调用clean_fields, clean, and validate_unique,在model里raise错误 ValidationError """ errors = {} if exclude is None: exclude = [] else: exclude = list(exclude) try: self.clean_fields(exclude=exclude) except ValidationError as e: errors = e.update_error_dict(errors) # Form.clean() is run even if other validation fails, so do the # same with Model.clean() for consistency. try: self.clean() except ValidationError as e: errors = e.update_error_dict(errors) # Run unique checks, but only for fields that passed validation. if validate_unique: for name in errors.keys(): if name != NON_FIELD_ERRORS and name not in exclude: exclude.append(name) try: self.validate_unique(exclude=exclude) except ValidationError as e: errors = e.update_error_dict(errors) if errors: raise ValidationError(errors)
clean_fields函数
def clean_fields(self, exclude=None): """ Cleans all fields and raises a ValidationError containing a dict of all validation errors if any occur. 清洗所有字段,并且抛出ValidationError异常,所有发生的错误都包含在一个字典中。 """ if exclude is None: exclude = [] errors = {} for f in self._meta.fields: if f.name in exclude: continue # Skip validation for empty fields with blank=True. The developer # is responsible for making sure they have a valid value. raw_value = getattr(self, f.attname) if f.blank and raw_value in f.empty_values: continue try: setattr(self, f.attname, f.clean(raw_value, self)) except ValidationError as e: errors[f.name] = e.error_list if errors: raise ValidationError(errors)
clean()函数
def clean(self): """ Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS. #clean函数是一个钩子,调用clean_fields就会调用clean函数, """ pass
数据字段正则判断
error_messages 自定义错误信息(字典类型),从而定制想要显示的错误信息; 字典健:null, blank, invalid, invalid_choice, unique, and unique_for_date 如:{'null': "不能为空.", 'invalid': '格式错误'} validators 自定义错误验证(列表类型),从而定制想要的验证规则 from django.core.validators import RegexValidator from django.core.validators import EmailValidator,URLValidator,DecimalValidator,\ MaxLengthValidator,MinLengthValidator,MaxValueValidator,MinValueValidator 如: test = models.CharField( max_length=32, error_messages={ 'c1': '优先错信息1', 'c2': '优先错信息2', 'c3': '优先错信息3', }, validators=[ RegexValidator(regex='root_\d+', message='错误了', code='c1'), RegexValidator(regex='root_112233\d+', message='又错误了', code='c2'), EmailValidator(message='又错误了', code='c3'), ] # Create your models here. class News(models.Model): title = models.CharField(max_length=10, error_messages={'c1': '.....'}, validators=[ RegexValidator(regex='root_\d+', message='错误了', code='c1'),] ) favor = models.ManyToManyField('User', through="Favor", through_fields=("new_obj", 'user_obj')) def clean(self): self.title
2、Model的总结
Model:具有强大的数据库操作(建表、确定表之间的关系、表的操作)
较弱的数据验证(专门针对字段定义错误、或者正则错误)
内置钩子数据验证(验证功能比较弱化,清洗字段主要是靠自定义错误)