首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Django-Taggit中扩展TagBase

在Django-Taggit中扩展TagBase
EN

Stack Overflow用户
提问于 2011-08-18 21:53:46
回答 1查看 1.1K关注 0票数 2

我已经创建了以下TagBase,每个类别都可以有子类别...这样行得通吗?如何在TaggableManager中重写它的add函数?

代码语言:javascript
复制
 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')
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-06-13 09:20:17

django-taggit/docs/custom_tagging.txt描述了如何。您必须使用指向TagBase子类的外键tag定义一个中间模型。

代码语言:javascript
复制
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)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7108533

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档