Search code examples
mysqldjangoamazon-web-servicesamazon-elastic-beanstalkmakemigrations

How to control table names created by Django migrate


Context: Django 1.7; MySQL 5.6.23; Running on AWS (not sure of exact Linux OS version)

I have a Django 1.7 project. When I do the initial makemigrations to build my DB locally on my Windows laptop, I get tables that are prefixed with my app name like this:

myapp_person (for Django class Person(models.Model))

myapp_personmap (for Django class PersonMap(models.Model))

When I makemigrations & migrate to the AWS Linux server, the tables are named like this:

MyApp_person

MyApp_personmap

Notice the unexpected CamelCase for the app-name prefix and the expected lower case for the rest of the table names.

My questions:

  1. What controls the appname prefix to the tables (e.g. "myapp_" in "myapp_person")?
  2. How can I get the migration to use all lowercase on AWS like it does locally on my Windows laptop?

Solution

  • To use your own custom table name, you need to define a db_table parameter in your models Meta option.

    From the Django docs on table names:

    To override the database table name, use the db_table parameter in class Meta.

    Query-1: What controls the appname prefix?

    If you have not defined a db_table option in your model's Meta class, then Django automatically derives a name using the app label and the class name of the model.

    From the official docs:

    Django automatically derives the name of the database table from the name of your model class and the app that contains it. A model’s database table name is constructed by joining the model’s “app label” – the name you used in manage.py startappto the model’s class name, with an underscore between them.

    For example:

    If you have an app xyz created by manage.py startapp xyz, a model defined as class Abc will have a database table named as xyz_abc.

    Query-2: Creating tables with custom table names

    If you want to use a custom table name, then you need to use the db_table option in your model Meta.

    Here, you can explicitly define the db table names in lowercase.

    class Person(models.Model):
    
        class Meta:
            db_table = '"myapp_person"' # define your custom name
    
    class PersonMap(models.Model):
    
        class Meta:
            db_table = '"myapp_personmap"' # define your custom name