Reputation: 585
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.
Upvotes: 4
Views: 770
Reputation: 13328
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)
Upvotes: 1