我有一个现有的具有多对多关系的 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/