django 如何为 postgresql 数据库中现有的多对多表定义模型

标签 django postgresql many-to-many

我有一个现有的具有多对多关系的 PostgreSQL 数据库,它是通过如下所示的连接表处理的。

我正在寻找应用 ManyToMany 字段类型,这会绕过这个连接/中间表吗?如何在我的 models.py 中正确配置它?我宁愿保留中间表。

# models.py
class Sample(models.Model):
    sample_id = models.AutoField(primary_key=True)
...

class JoinSampleContainer(models.Model):
    id = models.AutoField(primary_key=True)
    container_id = models.ForeignKey(Container, db_column='container_id', on_delete = models.PROTECT)
    sample_id = models.ForeignKey(Sample, db_column='sample_id', on_delete = models.PROTECT)
...

class Container(models.Model):
    container_id = models.AutoField(primary_key=True)

最佳答案

在您的一个模型(例如 Sample)上定义 ManyToManyField,将 through 选项指定为 documented here :

class Sample(models.Model):
    id = ...
    containers = models.ManyToManyField(Container, through='JoinSampleContainer', through_fields=('sample_id', 'container_id'),
        related_name='samples')

注意:您应该为模型中的字段命名以提高可读性(并使用 db_column 指定所使用的 DB 列)。使用 id 而不是 sample_id,使用 sample.id 而不是 sample.sample_id 更具可读性。并使用 sample 而不是 sample_id,在直通模型上使用 container 而不是 container_id

关于django 如何为 postgresql 数据库中现有的多对多表定义模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54763524/

相关文章:

python - 为什么 Django 的用户模型将电子邮件字段设置为非唯一?

python - Django 比较来自不同数据库的查询集

postgresql - Azure DevOps CI 中 Azure 服务集成的自动化集成测试

sql - 在 Postgresql 中按一级取消嵌套多维数组

mysql - 多对多选择

django - 对于 Facebook 和 Twitter 集成,最推荐的 django/oauth 包是什么?

postgresql - 什么时候应该在没有时区的情况下创建 PostgreSQL 时间戳?

entity-framework - 你如何在 .net Entity Framework 中插入或更新多对多表

python - 来自 ManyToMany 关系的查询集

python - Django 单元测试 : How to test concurrent database operations?