【Django】不需要在表名中包含应用程序名称

首先

如果将Django的models.py迁移到数据库并创建表格,那么表格的名称前面会加上应用程序的名称。
假设我们创建了一个名为”app”的应用程序,并使用python manage.py startapp app命令,
如果创建了如下所示的models.py文件:

class Reporter(models.Model):
    full_name = models.CharField(max_length=70)

当您直接查看数据库时,表名将显示为app_reporter。

postgres-# \dt
                   List of relations
 Schema |            Name            | Type  |  Owner
--------+----------------------------+-------+----------
 public | app_reporter               | table | postgres
 public | auth_group                 | table | postgres
 public | auth_group_permissions     | table | postgres
 public | auth_permission            | table | postgres
 public | auth_user                  | table | postgres
 public | auth_user_groups           | table | postgres
 public | auth_user_user_permissions | table | postgres
 public | django_admin_log           | table | postgres
 public | django_content_type        | table | postgres
 public | django_migrations          | table | postgres
 public | django_session             | table | postgres
(11 rows)

出于将来的便利考虑,我研究了删除表名中应用程序名称的方法,并将结果记录下来。

环境

    • Django==4.2.6

 

    DB postgres

操作步驟

在models.py文件中,在相应的Meta类中添加db_table = ‘表名’。

class Reporter(models.Model):
    full_name = models.CharField(max_length=70)

    def __str__(self):
        return self.full_name
    
    class Meta:
        db_table = 'Reporter'

已更改为指定的表名称。

 Schema |            Name            | Type  |  Owner
--------+----------------------------+-------+----------
 public | Reporter                   | table | postgres

结束

为了方便维护,希望将表格名称命名得更加简洁易懂。

广告
将在 10 秒后关闭
bannerAds