如何在同一模型中拥有两个标签字段,即两个可标签管理器?

How to have two tag fields i.e. two Taggable Managers in the same model?

我有一个上传文件的模型,我现在需要在该模型中有两个标签字段。一个用于用户标签,一个用于管理标签。我尝试了几种解决方案,但都没有用。

现在这是我的代码,但它不起作用。不确定这是否要创建两个单独的表,一个用于用户标签,一个用于管理标签,因此我们将不胜感激。另外,如果你能向我解释一下我在做什么,因为我迷路了。

class UserTags(CommonGenericTaggedItemBase, TaggedItemBase):
    object_id = models.CharField(max_length=50, db_index=True)
    objects = models.Manager()

class BaseTag(TagBase):
    pass


class AdminTags(CommonGenericTaggedItemBase, TaggableManager):
    object_id = models.CharField(max_length=50, db_index=True)
    tag = models.ForeignKey(BaseTag, on_delete=models.CASCADE)
    objects = models.Manager()


# Model for all uploaded files
class Uploaded(models.Model):
    objects: models.Manager()
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="users")
    time_uploaded = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=50)
    file = models.FileField(upload_to=MEDIA_ROOT)
    tag = TaggableManager(blank=True, through=UserTags, related_name='user_tags')
    tags = TaggableManager(blank=True, through=AdminTags, related_name='admin_tags')
    additional_description = models.CharField(max_length=50, blank=True)

    def __str__(self):
        return f"{self.name} {self.file}"

我会尝试这样实现它。

from django.db import models
from taggit.managers import TaggableManager
from taggit.models import TaggedItemBase, ItemBase


class AdminTag(ItemBase):
    pass


class UserTag(ItemBase):
    pass


class ThroughAdminTag(TaggableManager):
    content_object = models.ForeignKey('AdminTag', on_delete=models.CASCADE)


class ThroughUserTag(TaggableManager):
    content_object = models.ForeignKey('UserTag', on_delete=models.CASCADE)


# Model for all uploaded files
class Uploaded(models.Model):
    objects = models.Manager()
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="users")
    time_uploaded = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=50)
    file = models.FileField(upload_to=MEDIA_ROOT)
    tag = TaggableManager(blank=True, through=ThroughUserTag, related_name='user_tags')
    tags = TaggableManager(blank=True, through=ThroughAdminTag, related_name='admin_tags')
    additional_description = models.CharField(max_length=50, blank=True)

    def __str__(self):
        return f"{self.name} {self.file}"

不确定 AdminTagUserTag 是否需要任何字段。理论上,从 ItemBase 继承它们应该涵盖这些内容。