Search code examples
djangopostgresqlmany-to-many

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


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)

Solution

  • 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.