我有以下型号:
class CodeSynonyms(models.Model):
code = models.ForeignKey(Codes, on_delete=models.CASCADE)
websites = models.ManyToManyField(Websites)
synonym = models.Charfield(max_length=10)
这个想法是网站使用特定代码的同义词。一个网站不能少有代码的同义词;各个网站可以共享特定代码的相同同义词。以下内容无效:
class Meta:
unique together = ('code', 'websites')
“'unique_together'指的是ManyToManyField'网站',但'unique_together'中不允许ManyToManyFields”“
是否有解决此问题的方法来保持M2M关系?拥有它会很方便
答案 0 :(得分:2)
您可以在through
中使用ManyToManyField
,并通过自定义的中间表将多对多关系连接起来。然后在其中添加unique_together
:
class CodeSynonyms(models.Model):
websites = models.ManyToManyField(Websites, through='WebsiteCode')
synonym = models.Charfield(max_length=10)
class WebsiteCode(models.Model):
code_synonym - models.ForeignKey(CodeSynonyms, on_delete=models.CASCADE)
website = models.ForeignKey(Websites, on_delete=models.CASCADE)
code = models.ForeignKey(Codes, on_delete=models.CASCADE)
class Meta:
unique together = ('code', 'website')