django - unique_together 和 M2M 字段

标签 django postgresql django-models

我有以下模型:

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 关系的问题?有了它会很方便

最佳答案

您可以在 ManyToManyField 中使用 through 并通过自定义中间表连接您的多对多关系。然后在此处添加 unique_together:

class CodeSynonyms(models.Model):
    # add through field
    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')

关于django - unique_together 和 M2M 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55196633/

相关文章:

python - 迁移中的 Django 设置

sql - 在 Postgres 中将日期转换为一年中的某一天

Django save() 覆盖,最佳实践 : on model, 表单或 View ?

Django - 如何将 InMemoryUploadedFile 转换为 ImageField 的 FieldFile?

python - Django 管理界面 : using horizontal_filter with inline ManyToMany field

JavaScript 错误 Uncaught SyntaxError : Unexpected identifier

postgresql - 微服务使 postgres 连接倍增

django-models - 保存方法中的 force_update

Python 2.7.2 作为 Debian 5 Lenny 的默认值,用于 Django 应用程序

sql - 在另一个计算 SELECT 列中使用计算 SELECT 列