【问题标题】:How to access the custom through model in django-taggit如何通过 django-taggit 中的模型访问自定义
【发布时间】:2014-11-15 23:13:41
【问题描述】:

如何在django-taggit中添加额外的信息到标签系统或通过模型访问?

我的模型'Post'有一个图像和一个TaggableManager,这样每个帖子(或图像)上可以有多个标签,用户可以通过标签搜索所有帖子。现在,我需要在每张图片上指定标记标签的位置(类似于用户在照片上的特定位置标记朋友的概念)。

我想我需要在 through 模型中添加额外的信息,因为坐标只属于帖子和标签的关系,而不属于标签本身。这是model.py(简化):

class TaggedPost(taggit.models.TaggedItemBase):
    content_object = models.ForeignKey('Post')
    x = models.IntegerField()
    y = models.IntegerField()

class Post(models.Model):
    image = models.ImageField(upload_to='p/%Y/%m/%d/')
    tags = TaggableManager(through=TaggedPost)

但是,我无法通过 TaggableManager 的 API 访问直通模型。是否可以读取数据?我不想建立另一个关系或映射表。

感谢您的任何建议。

【问题讨论】:

    标签: django model tags django-taggit


    【解决方案1】:

    我在 taggit 的谷歌论坛上问过,但没有回复。这是我最后的解决方案(可能不是最好的)

    我像这样构建自己的 GenericTaggedItemBase:

    class GenericPostTaggedItemBase(ItemBase):
        content_object = models.ForeignKey('Post', related_name='%(class)s')
        x = models.IntegerField(null=True, default=None, blank=True)
        y = models.IntegerField(null=True, default=None, blank=True)
    
        class Meta:
            abstract = True
    

    然后类似于 Taggit 中的 TaggedItem:

    class PostTaggedItem(GenericPostTaggedItemBase, TaggedItemBase):
    
        class Meta:
            verbose_name = _("Tagged Item")
            verbose_name_plural = _("Tagged Items")
    

    在我的 Post 模型中:

    class Post(models.Model):
        # whatever fields go here
        tags = TaggableManager(through=PostTaggedItem)
    

    评估数据:

    Post post = Post.objects.get(pk=1)
    models = post.posttaggeditem.all()
    for item in models:
        # here is item.x and item.y
    

    这里的关键是GenericPostTaggedItemBase 中的related_name。它必须是 %(class)s 或类似的(请参阅 taggit 中的源代码)。这样通用基础可以与其他类型的标签一起使用,如果你有的话。此外,这对于抽象类来说是一种“推荐”(不要对抽象类使用固定的相关名称)。有关详细信息,请搜索 related_name 和 %(class)。我将跳过这里。

    如果您有任何想法或建议,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-09
      • 1970-01-01
      • 2014-12-28
      • 1970-01-01
      • 1970-01-01
      • 2012-09-23
      • 2013-06-12
      相关资源
      最近更新 更多