如何更改由Django创建的数据库的列名(来自models.py)? [英] How to change the Column Names of a database created by Django (from models.py)?

查看:300
本文介绍了如何更改由Django创建的数据库的列名(来自models.py)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在本地PHPMyAdmin中有一个MySQL数据库,其中的DB和Tables已经填充了数据.我现在必须将该数据库移植到django中.

So I have a MySQL Database in my local PHPMyAdmin with DBs and Tables already filled in with data. I have to now port that DB into django.

例如,数据库中表的名称为"ratings".因此,使用django,我必须首先创建一个名为something的应用程序(假设为网站"),然后可以将模型评级添加到该应用程序.这将在数​​据库中创建一个表"website_ratings".这不是我想要的,我希望表格的名称仅是等级.

For example, the name of a table in the DB is "ratings". So using django, I have to first create an app named something (let's say "website") and then I can add the model ratings to that app. This creates a table "website_ratings" in the DB. Which is not what I want, I want the name of the table to be just ratings.

有什么办法可以做到这一点?

Is there any way to get this done?

推荐答案

您可以在模型类中设置表名和列名.这是一个示例:

You can set the table name and column names in the model class. Here is an example:

class Rating(models.Model):
    field_name = models.CharField(db_column='column_name')
    # other fields

    class Meta:
        db_table = 'ratings'

这意味着您可以为每个字段指定一个列名称,该名称可以不同于该字段名称.在Meta类中,您可以指定表名.否则,Django会根据应用标签和模型类名称自动创建它.

It means for every field you can specify a column name, which can be different than the field name. In the Meta class you can specify the table name. Otherwise Django creates it automatically out of the app label and the model class name.

如果它是旧数据库,并且要创建模型类,则可以使用以下命令:

If it is a legacy database and you want to create model classes, you can use the following command:

python manage.py inspectdb > models.py

通常情况下,您必须根据需要编辑文件.

Usually you'll have to edit the file after that according to your needs.

这篇关于如何更改由Django创建的数据库的列名(来自models.py)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆