Created
January 30, 2020 17:58
-
-
Save tomleo/5a81fc34f0e29dff9ece871c1709c479 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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