Skip to content

Instantly share code, notes, and snippets.

@tomleo
Created January 30, 2020 17:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomleo/5a81fc34f0e29dff9ece871c1709c479 to your computer and use it in GitHub Desktop.
Save tomleo/5a81fc34f0e29dff9ece871c1709c479 to your computer and use it in GitHub Desktop.
class Foo(models.Model):
def object_validation(
cls, some_values
) -> Optional[str]:
"""
Validation logic when creating a Foo record
If creation is via a model serializer's is_valid method this function
will get triggered via the clean method.
If creation is not via a model serializer's is_valid method this
function will get triggered via the save method.
"""
if not some_value == "somethong":
return FOO_ERROR_MSG_SOMETHING_GOES_HERE
return None
def clean(self):
"""
`is_valid` calls on model serializers should trigger this validation prior to saving
"""
error_msg = self.content_object_validation(
some_value
)
if error_msg:
raise ValidationError(error_msg)
def save(self, *args, **kwargs):
"""
Ensure new objects are valid prior to save.
"""
if not self.id:
error_msg = self.content_object_validation(
some_value
)
if error_msg:
raise IntegrityError(error_msg)
super().save(*args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment