简体   繁体   中英

What is the main difference between clean and full_clean function in Django model form?

Django 模型中 clean 和 full_clean 函数的主要区别是什么?

From the documentation :

Model.full_clean( exclude=None, validate_unique=True ) :

This method calls Model.clean_fields() , Model.clean() , and Model.validate_unique() (if validate_unique is True ), in that order and raises a ValidationError that has a message_dict attribute containing errors from all three stages.

Model.clean() :

This method should be used to provide custom model validation, and to modify attributes on your model if desired.

For more detailed explanation, have a look at the Validating objects section of the documentation.

they are not against each other usually you call Model.full_clean() to be able to trigger Model.clean() for costume validation for example:

from django.core.exceptions import ValidationError
from django.db import models


class Brand(models.Model):
    title = models.CharField(max_length=512)

    def clean(self):
        if self.title.isdigit():
            raise ValidationError("title must be meaningful not only digits")

    def save(self, *args, **kwargs):
        self.full_clean()
        return super().save(*args, **kwargs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM