[Django]-Deleting the tags that are not used by any other object

1πŸ‘

βœ…

I don’t think you should be using instance.tag_id in the filter. Try just using instance.tag. Then when finding the tag object you can replace –

t = Tag.objects.get(pk=instance.tag_id)

with –

t = instance.tag

Adding _id to a field is a shortcut for getting the primary key of an object. So instance.tag is the tag object and instance.tag_id is the primary key of the tag object.

The whole thing would be more succinct –

# Delete the tags that are not used by any other object
from django.db.models.signals import post_delete

def after_deleting(sender, instance, **kwargs):
    if not TaggedItem.objects.filter(tag=instance.tag):
        print "Deleting tag", instance
        instance.tag.delete()

post_delete.connect(after_deleting, sender=TaggedItem)
πŸ‘€Aidan Ewen

Leave a comment