Skip to content

Instantly share code, notes, and snippets.

@avi-perl
Last active July 10, 2023 03: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 avi-perl/9b4932ce6e842bfcb0a2751d75d61c0b to your computer and use it in GitHub Desktop.
Save avi-perl/9b4932ce6e842bfcb0a2751d75d61c0b to your computer and use it in GitHub Desktop.
Natural integration of business logic with a Django Model
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)
{
"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