如何向标签系统添加额外信息或通过django-taggit中的模型访问?
我的模型“Post”有一个图像和一个TaggableManager,以便每个帖子(或图像)上可以有多个标签,并且用户可以通过标签搜索所有帖子。现在,我需要指定每个图像上标记的位置(类似于用户在照片上的特定位置标记 friend 的概念)。
我认为我需要向 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访问through模型。可以读取数据吗?我不想构建另一个关系或映射表。
感谢您的任何建议。
最佳答案
我在 taggit 的 Google 论坛上提问,但没有回复。这是我最后的解决方案(可能不是最好的)
我像这样构建自己的 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")
在我的帖子模型中:
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
中的 lated_name
。它必须是 %(class)s
或类似的(请参阅 taggit 中的源代码)。这样通用基础就可以与其他类型的标签一起使用(如果有的话)。另外,这对于抽象类来说是“推荐”的(不要对抽象类使用固定的 related_name )。有关详细信息,请搜索 related_name 和 %(class)。我将在这里跳过这个。
如果您有任何想法或建议,请告诉我。
关于django - 如何通过django-taggit中的模型访问自定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25966434/