重写django-taggit标签使其始终为小写

0 投票
2 回答
965 浏览
提问于 2025-04-19 22:39

我找不到关于在模型中使用多个标签的好答案或解决方案。我找到的唯一接近的内容是这个:

如何限制django-taggit只接受小写字母的单词?

这是我现在的代码:

from taggit.managers import TaggableManager
from taggit.models import TaggedItemBase


class TaggedStory(TaggedItemBase):
    content_object = models.ForeignKey("Story")


class TaggedSEO(TaggedItemBase):
    content_object = models.ForeignKey("Story")


class Story(models.Model):
    ...

    tags = TaggableManager(through=TaggedStory, blank=True, related_name='story_tags')

    ...

    seo_tags = TaggableManager(through=TaggedSEO, blank=True, related_name='seo_tags')

2 个回答

0

在应用程序的 utils 文件里,比如说在 (blog --> init.py) 这个文件中,定义一个函数,内容如下:

def comma_splitter(tag_string):
"""把每个标签都转换成小写"""
return [t.strip().lower() for t in tag_string.split(',') if t.strip()]

然后,在 settings.py 文件中,定义并覆盖默认的 taggit 设置,内容为:
TAGGIT_TAGS_FROM_STRING = 'blog.init.comma_splitter'

1

我通常在表单层面上实现这个功能:

def clean_tags(self):
    """
    Force all tags to lowercase.
    """
    tags = self.cleaned_data.get('tags', None)
    if tags:
        tags = [t.lower() for t in tags]

    return tags

这其实要看你怎么理解这个问题。我觉得这个解决方案挺好的,因为我把它看作是一个验证问题。如果你把它看作是数据完整性的问题,那我能理解你为什么想在模型层面上处理。在这种情况下,最好的办法就是对taggit模块进行子类化,直到你可以重写Tag.save()这个方法。

撰写回答