如何控制Django migrate创建的table个名字

How to control table names created by Django migrate

上下文: 姜戈 1.7; MySQL 5.6.23; 运行 在 AWS 上(不确定确切的 Linux OS 版本)

我有一个 Django 1.7 项目。当我执行初始 makemigrations 以在我的 Windows 笔记本电脑上本地构建我的数据库时,我得到 tables 以我的应用程序名称为前缀,如下所示:

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

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

当我进行迁移并迁移到 AWS Linux 服务器时,table 的名称如下:

MyApp_person

MyApp_personmap

请注意应用程序名称前缀的意外 CamelCase 和其余 table 名称的预期小写。

我的问题:

  1. 什么控制 table 的应用名称前缀(例如“myapp_person”中的“myapp_”)?
  2. 如何让迁移在 AWS 上使用所有小写字母,就像在我的 Windows 笔记本电脑上本地一样?

您可以使用 db_table from Model Meta Options:

class MyModel(models.Model):

...

class Meta:
    db_table = 'my_custom_table_name'

要使用您自己的自定义 table 名称,您需要在模型 Meta 选项中定义一个 db_table 参数。

来自 table names:

上的 Django 文档

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

问题1:appname前缀是什么控制的?

如果您没有在模型的 Meta class 中定义 db_table 选项,那么 Django 会自动使用 app label 和 class 模型名称。

来自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.

例如:

如果您有一个由 manage.py startapp xyz 创建的应用 xyz,定义为 class Abc 的模型将有一个名为 table 的数据库 xyz_abc.

查询 2:使用自定义 table 名称创建 tables

如果您想使用自定义 table 名称,则需要在您的模型 Meta 中使用 db_table 选项。

在这里,您可以明确定义小写的数据库 table 名称。

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