django taggit扩展属性

2019/7/27 posted in  python

项目中的taggit需要给标签添加新的功能

django-taggit扩展tag字段

class MyCustomTag(TagBase):
    # ... fields here

    tag_chinese = models.CharField('tag_chinese', null=True, blank=True, max_length=255)

    class Meta:
        verbose_name = _("Tag")
        verbose_name_plural = _("Tags")

    # ... methods (if any) here



class TaggedWhatever(GenericTaggedItemBase):
    # TaggedWhatever can also extend TaggedItemBase or a combination of
    # both TaggedItemBase and GenericTaggedItemBase. GenericTaggedItemBase
    # allows using the same tag for different kinds of objects, in this
    # example Food and Drink.

    # Here is where you provide your custom Tag class.
    tag = models.ForeignKey(MyCustomTag,
                            related_name="%(app_label)s_%(class)s_items", on_delete=models.CASCADE)

# 最后在自己的字段中添加相应的字段即可配置成功

class Dribbble(models.Model):
...
    tag = TaggableManager(through=TaggedWhatever)

形成的数据库如下:

collect_mycustomtag数据库

collect_taggedwhatever

这样就可以给标签添加一个tag字段

在添加以及列表页显示自己的标签字段

在collect app中添加utils.py文件

def comma_splitter(tag_string):
    tags = []
    tags_with_c = tag_string.split(',')
    for tag_with_c in tags_with_c:
        if '(' in tag_with_c:
            tag = tag_with_c.split('(')[0]
            tags.append(tag.strip().lower())
        else:
            tags.append(tag_with_c.strip().lower())
    return tags


def comma_joiner(tags):
    tag_str = ""
    for t in tags:
        if t.tag_chinese:
            tag_str = tag_str + f"{t.name}({t.tag_chinese}),"
        else:
            tag_str = tag_str + f"{t.name}(),"
    return tag_str

最后在settings.py文件中添加相应的配置

TAGGIT_TAGS_FROM_STRING = 'collect.utils.comma_splitter'
TAGGIT_STRING_FROM_TAGS = 'collect.utils.comma_joiner'

详情可以参考

django-taggit官方说明文档