重写Djangotaggit标记,使其始终为小写

2024-10-01 07:31:13 发布

您现在位置:Python中文网/ 问答频道 /正文

对于一个模型中的多个标记,我找不到一个好的答案或解决方案。我找到的唯一线索是:

How can I limit django-taggit to accept only lowercase words?

以下是我当前的代码:

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')

Tags: fromimportobjectmodelstagstaggitcontentclass
1条回答
网友
1楼 · 发布于 2024-10-01 07:31:13

我通常在表单级别实现这一点:

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模块的子类化到可以重写的程度标记保存(). 在

相关问题 更多 >