Skip to content

Instantly share code, notes, and snippets.

@LowerDeez
Last active October 24, 2017 08:09
Show Gist options
  • Save LowerDeez/ba3b3b1d6a8cef7d094bb0177c03075e to your computer and use it in GitHub Desktop.
Save LowerDeez/ba3b3b1d6a8cef7d094bb0177c03075e to your computer and use it in GitHub Desktop.
Django. GEnericRelation. Removing objects of Generic Relation model if content_object has been removed
# Article - your model
# Action, Like - Generic Relation models
# Deleting action and likes, associated with article, if we deleting article
def deleted_gfk_Action(sender, instance, using, **kwargs):
ctype = ContentType.objects.get_for_model(sender)
try:
action_objs = Action.objects.filter(target_ct=ctype, target_id=instance.id)
like_objs = Like.objects.filter(content_type=ctype, object_id=instance.id)
except Action.DoesNotExist:
pass
except Like.DoesNotExist:
pass
else:
action_objs.delete()
like_objs.delete()
pre_delete.connect(deleted_gfk_Action, sender=Article, dispatch_uid='article_delete_signal')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment