django how to define models for existing many to many tables in postgresql database

江枫思渺然 提交于 2021-02-08 08:51:51

问题


I have an existing PostgreSQL database with a many to many relationship, it is handled through a join table as below.

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)

回答1:


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')

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.



来源:https://stackoverflow.com/questions/54763524/django-how-to-define-models-for-existing-many-to-many-tables-in-postgresql-datab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!