kelvinfix
kelvinfix

Reputation: 3075

Django admin many to many table name

Can I specify the name I want for the many to many table?

Upvotes: 11

Views: 8980

Answers (3)

mcursa-jwt
mcursa-jwt

Reputation: 130

msb's answer works great, however if (like me) you needed to set it to the same name (because of known naming issues mysql-django backend), you would need to register it in a migration.

The new problem is that Django will try to create a new table of the same name when you run the automatically created new migrations, which will throw a "database already exists" error.

You would thus need to go back to the original migration where that ManyToManyField was created and add what you included there.

For example:

app/models.py:

class revision(models.Model):
    revision_id = models.AutoField(primary_key=True)
    issue_list = models.ManyToManyField(issue, related_name='revisions', db_table='app_revision_issue_list')

# In here, 'app_revision_issue_list' was originally created automatically, 
# however lets say you need to explicitly declare it (compatible across all environments)

app/migrations/0003_.py:

migrations.CreateModel(
            name='revision',
            fields=[
                ('revision_id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('issue_list', models.ManyToManyField(issue, related_name='revisions', db_table='app_revision_issue_list')), 
                # originally no db_table parameter in this migration operation
            ],
        ),

If you edit the original migration where the field was created, there is no further need to makemigrations and migrate.

Upvotes: 0

msb
msb

Reputation: 4438

You define the table name using the db_table option when declaring the ManyToManyField attribute. See example below:

class revision(models.Model):
    revision_id = models.AutoField(primary_key=True)
    issue_list = models.ManyToManyField(issue, related_name='revisions', db_table='issue_revision')

related_name is the field by which this class will be seen by issue, meaning, you will access it as my_issue.revisions(). And the table being used in the DB is named issue_revision.

Upvotes: 2

Peter Rowell
Peter Rowell

Reputation: 17713

Yes. See Table Names for all of the exciting details.

Update: OK, then perhaps the related_name option is what you are looking for. There are some caveats covered here.

Updatex2: OK, Kelvin gets a star for answering his own question! It's been an age since I perused the Django Meta Model Options, but, in retrospect, that's where we should have started.

BTW, wandering through the django/db/ code on only half a cup of coffee is definitely a challenge.

Upvotes: 3

Related Questions