Created
February 6, 2023 21:36
-
-
Save bukowa/a5e431a60c773463b7678f3b7c348b1d to your computer and use it in GitHub Desktop.
django cascade on related change foreign key
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 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