提取特定内容类型使用的标签

时间:2018-09-26 17:57:48

标签: python django django-contenttypes

我正在Django's contenttypes framework之上构建自定义标记系统。

我的模型如下:

class Tag(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    slug = models.SlugField(verbose_name=_("Slug"), max_length=100)
    photo = models.ImageField(upload_to="tags", blank=True)
    status = models.CharField(
        max_length=10, choices=TAG_STATUSES, default=TAG_STATUS_UNREVIEWED
    )
    language = models.CharField(
        max_length=7, choices=settings.LANGUAGES, default="en"
    )  # 7 for zh-hant, for example
    creator = models.ForeignKey(
        "accounts.User",
        on_delete=models.CASCADE,
        default="4c44d45e-6d25-41e8-846e-2a417822417b",
    )
    site = models.ForeignKey(Site, on_delete=models.CASCADE)
    parent = models.ForeignKey(
        "self", blank=True, null=True, on_delete=models.CASCADE
    )  # null indicates root category
    usages = models.ManyToManyField(
        ContentType, through="TagUsage"
    )  # Tells us which sections are using the tag. We don't want to display 'Forums' tags as tags in 'Tickets', for example, unless they are actually used in both places

    def __str__(self):
        return self.slug

    class Meta:
        unique_together = ("slug", "site")

class TagUsage(models.Model):
    tag = models.ForeignKey(Tag, on_delete=models.CASCADE)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    counter = models.BigIntegerField() # How many items using the tag for the given content type (instead of counting on every request)


class TaggedItem(models.Model):
    # id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.UUIDField()
    content_object = GenericForeignKey("content_type", "object_id")
    tag = models.ForeignKey(Tag, on_delete=models.CASCADE)

所以我的问题是,如何列出特定内容类型中使用的标签?

0 个答案:

没有答案