Django如何为PostgreSQL数据库中现有的许多表定义模型 [英] django how to define models for existing many to many tables in postgresql database
问题描述
我有一个具有多对多关系的现有PostgreSQL数据库,它通过如下的联接表进行处理.
I have an existing PostgreSQL database with a many to many relationship, it is handled through a join table as below.
我要应用ManyToMany字段类型,这会绕过此联接/中间表吗?如何在我的models.py中正确配置它?我宁愿保留中间表.
I'm looking to apply the ManyToMany Field type, does this bypass this join/intermediate table? How do I correctly configure it in my models.py? I'd rather keep the intermediate table.
# 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
选项作为此处记录:
Define the ManyToManyField
on one of your models (e.g. Sample
) specifying a through
option as 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
.
Note: You should name the fields in your models for readability (and use db_column
to specify the DB column that is used). Use id
instead of sample_id
, it's much more readable to use sample.id
instead of sample.sample_id
. And use sample
instead of sample_id
, resp container
instead of container_id
on the through model.
这篇关于Django如何为PostgreSQL数据库中现有的许多表定义模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!