0

我无法为模型中的多个标签找到好的答案或解决方案。我发现唯一接近的是:

如何限制 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')
4

2 回答 2

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() 的程度。

于 2014-09-05T16:05:53.910 回答
0

在 appname --> 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. 初始化.comma_splitter'

于 2020-08-06T04:14:25.403 回答