4

我正在尝试修改此文件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.

您的帮助将不胜感激。

4

1 回答 1

1

我认为您不应该instance.tag_id在过滤器中使用。尝试仅使用instance.tag. 然后在找到可以替换的标签对象时 -

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

和 -

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)
于 2012-12-10T07:31:55.033 回答