What dose clean functions do in model django? NOT IN FORMS

I was reading THIS-SOLUTION and I wonder what dose "clean function" do ?

is clean where we should put our checkings ?


then I found this picture : enter image description here

so we have bunch of clean functions , I just want to know what they do . and is it correct to use "clean" if we want to add a filter which makes sure we wont have more than x object from one model(table)?


I think using " def save() " seems more suitable to solve this kind of checking but Im not sure.

The clean method in Django model is used for doing model wide checks (validations). Django DB models have one more method called clean_fields which runs the clean method on every field and raises Validation error based on field if there is any error. So, the errors raised by clean_fields method will be field-based like:

{
    "name": "Invalid name format",
    ...
}

But the clean method raises Non Field Errors, that means errors are not associated with any fields. Raised errors might be like:

{
    "non_field_errors: [
        "Invalid name format"
    ]
}

(Note: The error formats here might differ.)

It makes sense to use clean function when we want to do some validations on the model fields. But as you mentioned your use case of restricting number of objects for a particular model, it should be a good choise to use save method on the model.

Example:

def save(self, *args, **kwargs):
    if not self.pk and MyModel.objects.count() >= 10:
        raise ValidationError("Cannot create more than 10 objects.")
    super().save(*args, **kwargs)

You can also do the same using clean method but then you need to ensure that clean method is executed before every save and it doesn't happen automatically then you will need to trigger it manually, may be by calling full_clean before every save. This overhead can be saved by using save method approach.

Вернуться на верх