【问题标题】:How to add extra column mysql database table in Django?如何在 Django 中添加额外的列 mysql 数据库表?
【发布时间】:2020-08-18 14:16:42
【问题描述】:

我是 Django 的新手。我正在为我的 django 项目使用 Mysql 数据库。我在 models.py 中创建了模型类。

在我的models.py中

from django.db import models

class AuthModel(models.Model):
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    email = models.CharField(max_length=255)
    username = models.CharField(max_length=255) 
    password = models.CharField(max_length=255)

我已使用以下命令将此字段迁移到我的 Mysql 数据库中

 Python manage.py makemigrations  
 Python manage.py migrate 

这是在我的数据库中制作表格,如下所示

现在,我想在表中再添加一列“user_type”。
我可以从数据库中手动添加“user_type”列,但它不会将“user_type”值插入表中。因为我的“AuthModel”中没有包含“user_type”列。
如果我将 user_type 包含到“AuthModel”中并运行迁移命令,但是它不起作用。我想将 user_type 列添加到我的表中。该怎么做?

【问题讨论】:

    标签: python django django-models django-forms django-views


    【解决方案1】:

    首先您应该在 models.py

    中添加该字段
    from django.db import models
    
    class AuthModel(models.Model):
        user_type = models.CharField(max_length=255)
    

    然后在 admin.py 中进行更改 通过在 models.py 中声明时添加字段名称 喜欢-

    class UAdmin(admin.ModelAdmin):
        dics = ('user_type')
    

    如果你有任何 form 文件,然后更改添加它, 然后去终端 -

    python manage.py makemigrations
    python manage.py migrate
    

    如果终端说-

    Please select a fix:
     1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
     2) Quit, and let me add a default in models.py
    

    然后按 1 并提供一个值。

    您的数据库将有新的 'user_type' 列。

    【讨论】:

      【解决方案2】:

      将新字段添加到您的模型并重新运行迁移命令:

      class AuthModel(models.Model):
           # ...
           user_type = models.CharField(max_length=255) # or whatever field you want
      

      然后重新运行:

      Python manage.py makemigrations  
      Python manage.py migrate 
      

      您的数据库将拥有新的user_type 列。

      【讨论】:

        猜你喜欢
        • 2020-03-24
        • 1970-01-01
        • 1970-01-01
        • 2012-10-25
        • 1970-01-01
        • 1970-01-01
        • 2012-07-14
        • 2019-11-12
        • 2019-04-15
        相关资源
        最近更新 更多