Last active
July 10, 2023 03:58
-
-
Save avi-perl/9b4932ce6e842bfcb0a2751d75d61c0b to your computer and use it in GitHub Desktop.
Natural integration of business logic with a Django Model
This file contains 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 BlogPostUtils: | |
def __init__(self, post): | |
self.post = post | |
def before_save(self) | |
self.post.content = bleach.clean(self.post.content) | |
class BlogPost(models.Model): | |
# Class to be used for utility functions related to this class | |
utils = BlogPostUtils | |
title = models.CharField(null=False, max_length=250) | |
content = models.TextField() | |
created_by = models.ForeignKey(User, on_delete=models.PROTECT) | |
created_date = models.DateTimeField(auto_now_add=True, null=False) | |
def save(self, *args, **kwargs): | |
if self.utils: | |
module = self.utils(self) | |
module.before_save() | |
return super().save(*args, **kwargs) | |
This file contains 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
{ | |
"title": "Django Business Logic", | |
"slug": "some-slug" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment