I am trying to modify this file https://github.com/alex/django-taggit/blob/master/taggit/models.py so that when a tag is not associated with any other object, it gets deleted.
Here’s what I added to the end of the file:
# ---
# 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 TaggedItem.objects.filter(tag=instance.tag_id).count() == 0:
print "Deleting tag", instance
t = Tag.objects.get(pk=instance.tag_id)
t.delete()
post_delete.connect(after_deleting, sender=TaggedItem)
It’s not working as expected. When I run it give this error:
Exception Type: DoesNotExist
Exception Value: Tag matching query does not exist.
Your help would be appreciated.
I don’t think you should be using
instance.tag_idin the filter. Try just usinginstance.tag. Then when finding the tag object you can replace –with –
Adding _id to a field is a shortcut for getting the primary key of an object. So
instance.tagis the tag object andinstance.tag_idis the primary key of the tag object.The whole thing would be more succinct –