2011-08-18 61 views
2

我創建了以下的TagBase,每個類別都可以有子類別... 這是否行之有效?我如何覆蓋TaggableManager中的add函數?在Django-Taggit中擴展TagBase

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

回答

2

django-taggit/docs/custom_tagging.txt描述瞭如何。您必須爲您的TagBase子類定義一個帶有外鍵tag的中介模型。

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)