Skip to content

Instantly share code, notes, and snippets.

@sirrobot01
Created September 8, 2021 21:33
Show Gist options
  • Save sirrobot01/7707428b0731253cafdfb71994e5d4fe to your computer and use it in GitHub Desktop.
Save sirrobot01/7707428b0731253cafdfb71994e5d4fe to your computer and use it in GitHub Desktop.
from django.db import models
class MentionModel(models.Model):
text_field_name = "text"
mention_handler = "handle_mention"
class Meta:
abstract = True
def __init__(self, *args, **kwargs):
super(MentionModel, self).__init__(*args, **kwargs)
self.old_mentions = self.get_mentions(getattr(self, self.text_field_name, ""))
self.new_mentions = []
def save(self, *args, **kwargs):
if self.pk:
self.new_mentions = [m for m in self.get_mentions(getattr(self, self.text_field_name, "")) if
m not in self.old_mentions]
else:
self.new_mentions = self.old_mentions
super(MentionModel, self).save(*args, **kwargs)
if self.new_mentions:
mention_handler = getattr(self, self.mention_handler)
mention_handler()
@staticmethod
def get_mentions(text: str):
return [t for t in text.split() if t.startswith("@") and len(t) > 1]
def handle_mention(self):
"""
This will handle either send_email or push notification or bla bla bla bla bla bla you get???????
:return: I don't know boss
"""
class TweetModel(MentionModel):
tweet = models.TextField(blank=True, null=True)
text_field_name = "tweet"
mention_handler = "handle_tweet_mentions"
def handle_tweet_mentions(self):
print(self.new_mentions)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment