我正在尝试修改此文件https://github.com/alex/django-taggit/blob/master/taggit/models.py,以便当标记与任何其他对象无关时,它会被删除。
这是我添加到文件末尾的内容:
# ---
# 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)
它没有按预期工作。当我运行它时会出现此错误:
Exception Type: DoesNotExist
Exception Value: Tag matching query does not exist.
我们将不胜感激。
答案 0 :(得分:1)
我认为你不应该在过滤器中使用instance.tag_id
。尝试使用instance.tag
。然后在找到标签对象时可以替换 -
t = Tag.objects.get(pk=instance.tag_id)
with -
t = instance.tag
将_id添加到字段是获取对象主键的快捷方式。因此instance.tag
是标记对象,instance.tag_id
是标记对象的主键。
整个事情会更简洁 -
# 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)