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:
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 inmanage.py startapp
– to 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
You can use db_table
from Model Meta Options:
class MyModel(models.Model):
...
class Meta:
db_table = 'my_custom_table_name'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With