Model.clean()
有什么区别方法和 Model.clean_fields()
方法?。我什么时候应该使用其中一个?
根据Model.clean_fields()
方法文档:
This method will validate all fields on your model. The optional exclude argument lets you provide a list of field names to exclude from validation. It will raise a ValidationError if any fields fail validation.
. . .
所以
Model.clean_fields()
方法用于验证字段 我的模型。根据
Model.clean()
方法文档:This method should be used to provide custom model validation, and to modify attributes on your model if desired. For instance, you could use it to automatically provide a value for a field, or to do validation that requires access to more than a single field
. . .
但是,该方法应该用于进行其他验证,但其中,您可以对不同的 进行验证。字段 .而在
Model.clean()
的 Django 示例中方法,对字段进行验证:class Article(models.Model):
...
def clean(self):
# Don't allow draft entries to have a pub_date.
if self.status == 'draft' and self.pub_date is not None:
raise ValidationError(_('Draft entries may not have a publication date.'))
# Set the pub_date for published items if it hasn't been set already.
if self.status == 'published' and self.pub_date is None:
self.pub_date = datetime.date.today()
例如,如果我想验证一个字段,我应该用两种方法中的哪一种来验证?
这些方法究竟应该用于什么?因为我不太明白为什么应该完全使用它们。提供示例以查看方法之间的差异,以准确了解应该使用哪些方法,这将非常有帮助。
最佳答案
if I want to validate a field, in which of the two methods should I do it?
然后您通常将其添加为 validator [Django-doc] :
from django.core.exceptions import ValidationError
def even_validator(value):
if value % 2:
ValidationError('The value should be even')
class MyModel(models.Model):
my_fields = models.IntegerField(validators=[even_validator])
.clean_fields()
method [Django-doc]然后将调用各个字段的清理方法和验证方法,您可以传递参数来指定是否要排除验证某个字段。但通常你不会覆盖 .clean_fields()
本身。.clean()
method [Django-doc]另一方面是涉及多个字段时使用的验证方法。你可以覆盖它,尽管在这种情况下你通常也调用 super().clean()
方法来执行在基类中定义的验证。
关于python - Model.clean() 与 Model.clean_fields(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61507845/