2011-08-18 3 views
2

다음 TagBase를 생성했으며 각 카테고리는 하위 카테고리를 가질 수 있습니다 ... 이 작업이 가능합니까? TaggableManager의 add 함수를 어떻게 오버라이드 할 수 있습니까?Dagango-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)