Python 如何在django中将通用外键与unique一起使用?

Python 如何在django中将通用外键与unique一起使用?,python,mysql,django,Python,Mysql,Django,我在Django中有两个模型,它们继承自一个抽象基类 例如,我的抽象基础模型是common_content,我的两个继承模型是article和interview class commonContent: slug = models.TextField(blank=True, null=True, validators=[validate_slug]) css = models.TextField(blank=True, null=True) html_content

我在Django中有两个模型,它们继承自一个抽象基类

例如,我的抽象基础模型是common_content,我的两个继承模型是article和interview

class commonContent:
     slug = models.TextField(blank=True, null=True, validators=[validate_slug])
     css = models.TextField(blank=True, null=True)
     html_content = models.TextField(blank=True, null=True)
     ..... and so on, there are few more properties related to meta tags

   class Meta:
    abstract = True

class Article(CommonContent):
   related_content = CommaSeparatedIntegerField(max_length=255, null=True, blank=True)

class Interview(CommonContent):
   related_content = CommaSeparatedIntegerField(max_length=255, null=True, blank=True)
现在我有了一个分类模型,我想链接到采访和文章(两者都有共同的分类)

以下是我的分类模型:-

class Category():
name = models.CharField(max_length=100, unique=True, validators=[validate_slug])
display_text = models.CharField(max_length=255, null=True, blank=True)
现在,我尝试在以下模型中使用通用外键将我的分类模型链接到文章和访谈:-

class CategoryCommonContentMapping(BaseModel):
    category = models.ForeignKey(Category, null=True, blank=True)
    limit= models.Q(app_label = 'binger', model = 'interview') | models.Q(app_label = 'binger', model = 'article')
    type = models.ForeignKey(ContentType, on_delete=models.CASCADE,limit_choices_to = limit,default='')
    object_id = models.PositiveIntegerField(default='')
    contentObject = GenericForeignKey('type', 'object_id')
    score = models.FloatField(default=0.0)
现在,我尝试以以下方式在该模型中同时使用unique:

class Meta:
    unique_together = (('category', 'type','object_id'),)
但是缺少了一些东西,我无法将我的文章/采访与我的分类联系起来


我是django的新手,在阅读文档时尝试过一些事情。因此,基本上我想要的是,我可以将类别链接到访谈/文章,这样我就可以根据页面上的类别对它们进行过滤,也就是说,当选择类别时,内容(访谈/文章)应该只对该类别可见。我已经编写了过滤代码,在使用通用键之前,它工作得很好(我将访谈/文章保留在同一个模型中)。

我将摆脱内容模型的继承,我将只使用单一类型的模型,并使用一个额外的列来定义记录的类型(文章,访谈)-当您添加新类型的内容(无需创建新的db表)时,这将为您提供更大的灵活性,而且您不需要任何GenericForeignKey,一切都将变得更简单。