Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2019
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. class Like(models.Model):
  2. TARGET_MODEL = 'TargetModel'
  3. user = models.ForeignKey(settings.AUTH_USER_MODEL)
  4. target = models.ForeignKey(TARGET_MODEL)
  5.  
  6. class Meta:
  7. abstract = True
  8.  
  9. class LikeForPost(Like):
  10. TARGET_MODEL = 'blog.Post'
  11.  
  12. class Like(models.Model):
  13. TARGET_MODEL = None # will be overridden in subclass
  14. user = models.ForeignKey(settings.AUTH_USER_MODEL)
  15.  
  16. @classmethod
  17. def on_class_prepared(cls):
  18. target_field = models.ForeignKey(cls.TARGET_MODEL)
  19. target_field.contribute_to_class(cls, 'target')
  20.  
  21. class Meta:
  22. abstract = True
  23.  
  24. class LikeForPost(Like):
  25. TARGET_MODEL = 'blog.Post'
  26.  
  27. from django.apps import AppConfig
  28. from django.db.models import signals
  29.  
  30. def call_on_class_prepared(sender, **kwargs):
  31. """Calls the function only if it is defined in the class being prepared"""
  32. try:
  33. sender.on_class_prepared()
  34. except AttributeError:
  35. pass
  36.  
  37.  
  38. class BlogConfig(AppConfig):
  39. name = 'blog'
  40.  
  41. def __init__(self, app_name, app_module):
  42. super(BlogConfig, self).__init__(app_name, app_module)
  43. # Connect programmatic class adjustment function to the signal
  44. signals.class_prepared.connect(call_on_class_prepared)
  45.  
  46. default_app_config = 'blog.apps.BlogConfig'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement