我创建了以下TagBase,每个类别都可以有子类别...... 这会有用吗?如何在TaggableManager中覆盖其添加功能?
class Category(TagBase):
parent = models.ForeignKey('self', blank=True, null=True,
related_name='child')
description = models.TextField(blank=True, help_text="Optional")
class Meta:
verbose_name = _('Category')
verbose_name_plural = _('Categories')
答案 0 :(得分:2)
django-taggit/docs/custom_tagging.txt描述了如何。您必须使用外键tag
为您的TagBase
子类定义中间模型。
from django.db import models
from taggit.managers import TaggableManager
from taggit.models import ItemBase
# Required to create database table connecting your tags to your model.
class CategorizedEntity(ItemBase):
content_object = models.ForeignKey('Entity')
# A ForeignKey that django-taggit looks at to determine the type of Tag
# e.g. ItemBase.tag_model()
tag = models.ForeignKey(Category, related_name="%(app_label)s_%(class)s_items")
# Appears one must copy this class method that appears in both TaggedItemBase and GenericTaggedItemBase
@classmethod
def tags_for(cls, model, instance=None):
if instance is not None:
return cls.tag_model().objects.filter(**{
'%s__content_object' % cls.tag_relname(): instance
})
return cls.tag_model().objects.filter(**{
'%s__content_object__isnull' % cls.tag_relname(): False
}).distinct()
class Entity(models.Model):
# ... fields here
tags = TaggableManager(through=CategorizedEntity)