Search code examples
sqldjangodjango-modelsmany-to-manydjango-orm

Django ManyToManyField Custom Structure


Is it possible to manually specify the structure of the table created by a ManyToManyField in Django?

I'm trying to integrate Django with an existing database, and want to be able to use the data in the existing table. It's not possible to alter the structure of the database as this would break the original app that uses the DB.

If it helps, here are the table definitions:

class People(models.Model):
    person_id  = models.CharField(db_column='PersonId', primary_key=True)
    first_name = models.CharField(db_column='FirstName')
    ...

class PersonCats(models.Model):
    category_id  = models.IntegerField(db_column='PersonCatId', primary_key=True)
    title = models.CharField(db_column='Title', max_length=50)
    ...

class PersonCatPeople(models.Model):   #No primary key on this table
    person_cat_id = models.IntegerField(db_column='PersonCatId)
    person_id     = models.CharField(db_column='PersonId')
    ...

Solution

  • I don't see any ManyToMany field in your models, but I think you're looking for the through options of ManyToManyField. You can specify a custom table to use between your two related tables, and you can define its structure (fields):

    An example here:

    from django.db import models
    
    class Person(models.Model):
        name = models.CharField(max_length=50)
    
    class Group(models.Model):
        name = models.CharField(max_length=128)
        members = models.ManyToManyField(Person, through='Membership', through_fields=('group', 'person'))
    
    class Membership(models.Model):
        group = models.ForeignKey(Group)
        person = models.ForeignKey(Person)
        inviter = models.ForeignKey(Person, related_name="membership_invites")
        invite_reason = models.CharField(max_length=64)
    

    This was taken from Django ManyToMany Docs