Skip to content

Instantly share code, notes, and snippets.

@bukowa
Created February 6, 2023 21:36
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 bukowa/a5e431a60c773463b7678f3b7c348b1d to your computer and use it in GitHub Desktop.
Save bukowa/a5e431a60c773463b7678f3b7c348b1d to your computer and use it in GitHub Desktop.
django cascade on related change foreign key
class CascadeOnRelatedChangeForeignKey(models.ForeignKey):
"""
ForeignKey that deletes all instances of the "related_name"
whenever the related instance changes.
For example while using this field in a token model, if the user
changes, all the tokens will be deleted.
"""
def contribute_to_related_class(self, cls, related):
from django.db.models.signals import post_save
from django.dispatch import receiver
related_name = related.get_accessor_name()
@receiver(post_save, sender=cls)
def on_user_change(sender, instance, created, **kwargs):
if not created:
getattr(instance, related_name).all().delete()
super().contribute_to_related_class(cls, related)
class Token(AbstractToken):
objects = TokenManager()
user = CascadeOnRelatedChangeForeignKey(
User,
on_delete=models.CASCADE,
related_name="tokens",
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment