Django-taggit防止不同模型之间的标签重叠

2024-10-02 08:20:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两种不同的型号。在

class MessageArchive(models.Model):
    from_user = models.CharField(null=True, blank=True, max_length=300)
    archived_time = models.DateTimeField(auto_now_add=True)
    label = models.ForeignKey(MessageLabel, null=True, blank=True)
    archived_by = models.ForeignKey(OrgStaff)
    tags = TaggableManager()

现在,我已经为消息定义了spamtodourgent标记。在

然后我有另一个模型:

^{pr2}$

我为模特儿定义了awesomelegendrockstar。可能没有更多的定义。在

很明显,我确实希望person和message的标记重叠。 我该怎么做呢?谢谢!在


Tags: from标记truemodel定义modelsnullclass
2条回答

你的情况,据我所知,你想要两种不同型号的标签不同的基本系列。 考虑到我不是taggit的专家,所以我提出的解决方案可能有点过于复杂,但这是第一个通过查看源代码让我想起的解决方案。 您可以通过扩展TaggableManager使用的TaggableRel类并向limit_choices_to参数添加一个条件来实现:

扩展TaggableRel

class CustomTaggableRel(TaggableRel):
    def __init__(self, field, model_name):
        super(TaggableRel, self ).__init__(field)
        self.limit_choices_to = {'content_type': model_name}

然后按以下方式扩展TaggableManager:

^{pr2}$

比你的模特们:

class PersonArchive(models.Model):
        .
        .
        .
        tags = CustomTaggableManager(model_name="PersonArchive")

这应该可以解决问题,没有尝试解决方案,我很快就写下来了,但这会让你走上正确的道路。在

您可以在ForeignKeyFields和ManyToManyFields上使用limit_choices_to特性。你的模型.py文件可能如下所示:

class PersonArchive(models.Model):
    tags_field = models.ManyToManyField(Tag, related_name="people_archives", limit_choices_to={'message_archives__isnull': True})

class MessageArchive(models.Model):
    tags_field = models.ManyToManyField(Tag, related_name="message_archives", limit_choices_to={'people_archives__isnull': True})

相关问题 更多 >

    热门问题