【问题标题】:Added another column to a model in Django, how do I update database?在 Django 中的模型中添加了另一列,如何更新数据库?
【发布时间】:2018-04-04 11:55:28
【问题描述】:

所以我更改了名称并在 django 中为模型添加了一列。

之前:

class MyApp(models.Model):
    id = models.AutoField(primary_key=True)
    aaa = models.CharField(max_length=100)
    bbb = models.CharField(max_length=100)

之后:

class MyApp(models.Model):
    id = models.AutoField(primary_key=True)
    first = models.CharField(max_length=100)
    second = models.CharField(max_length=100)
    third = models.CharField(max_length=100)

我在 MyApp 的视图、模型和序列化程序中进行了这些更改,但是当我尝试访问我的新 API 端点时,它失败了,因为数据库不包含新的列名。如何更新数据库以反映我的新模型? (我不关心这个模型的任何数据,所以我可以擦除它)。不知道该怎么做

【问题讨论】:

  • 愚蠢的问题,但是您是否进行了迁移并随后迁移了?
  • @AlexanderTyapkov 我进行了迁移,我选择的应用程序的迁移已成功生成(我也检查过,它生成了文件夹),但是当我去迁移时它说没有检测到任何更改所以我想它一定是别的东西。
  • 听起来像是未应用的迁移。尝试运行迁移并指定应用程序的名称 -> python manage.py migrate your_app_name
  • @AlexanderTyapkov 仍然没有应用迁移
  • 您之前是否为该应用进行过迁移?

标签: django python-3.x django-rest-framework


【解决方案1】:

确保运行命令

python manage.py makemigrations appname

python manage.py migrate appname

如果你得到表已经存在运行命令

python manage.py migrate --fake appname

这解决了我遇到的问题。 https://docs.djangoproject.com/en/1.11/topics/migrations/#initial-migrations

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-10-17
  • 2021-01-04
  • 2022-01-16
  • 1970-01-01
  • 2021-08-31
  • 2021-04-06
  • 2021-10-06
  • 2013-08-09
相关资源
最近更新 更多