【问题标题】:Django migration is not changing database in AWS Elastic BeanstalkDjango 迁移不会更改 AWS Elastic Beanstalk 中的数据库
【发布时间】:2021-05-21 19:54:53
【问题描述】:

我已经使用 AWS Elastic Beanstalk 部署了我的 Djnago 应用程序。我添加了一些数据,一切正常。然后我增加了 model.py 中 CharField 之一的 ma​​x_length。我已经使用 'eb deploy' 命令再次部署了该应用程序。但它并没有增加数据库中的字段长度。如果我尝试添加大于 10 的 subject_id,我会收到此错误:django.db.utils.DataError: value too long for type character varying(10)

Model.py:

class Subject(models.Model):
        #subject_id = models.CharField(max_length=10, blank=True)
        subject_id = models.CharField(max_length=50, blank=True)

0001_initial.py:

#Generated by Django 3.0.4 on 2021-02-18 18:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
    initial = True
    dependencies = [
        ('accounts', '0001_initial'),]
    operations = [
        migrations.CreateModel(
            name='Subject',
            fields=[('subject_id', models.CharField(blank=True, max_length=50)),],),]

我在 .ebextensions/django_build.config 文件中添加了迁移命令。迁移文件夹中的 0001_initial.py 文件显示了更改。但它没有在数据库中更新(AWS RDS postgresql)。我检查了 postgresql 数据库中的 django_migrations 表。它显示了我第一次创建实例时发生的最后一次迁移。

我需要更改现有数据库中 Subject 模型的 subject_id 字段长度。任何帮助将不胜感激。

.ebextensions/django_build.config:

container_commands:
  01_create_log_folder:
    command: "mkdir -p log && chown webapp:webapp -R log"

  02_source_env:
    command: "source /etc/profile.d/sh.local"
    leader_only: true  
    
  03_database_migrations:
    command: "source /var/app/venv/*/bin/activate && python3 manage.py makemigrations --noinput && python3 manage.py migrate --noinput && deactivate"
    leader_only: true

django_migrations 表:

select * from django_migrations;
 id |       app       |                   name                   |            applied            
----+-----------------+------------------------------------------+-----------------------
 28 | fileupload      | 0001_initial                             | 2021-01-22 11:42:40.726471+00

【问题讨论】:

    标签: python django amazon-web-services amazon-elastic-beanstalk django-migrations


    【解决方案1】:

    由于您修改后的迁移与您已应用的迁移具有相同的名称 (0001_initial),因此不会执行它。您需要:

    • 创建一个新的迁移 (0002_new_migration) 来更改您在第一个迁移中创建的字段

    • 首先回滚您的迁移,然后应用修改后的迁移

    要回滚您的迁移,您需要通过 SSH 连接到 ELB 实例:

    Login via SSH - check your AWS console for specific instructions
    

    然后运行以下命令重置 accounts 迁移

    source /opt/python/run/venv/bin/activate
    source /opt/python/current/env
    cd /opt/python/current/app
    ./manage.py migrate accounts zero
    

    下次部署时,您将从头开始accounts 模型,并且您的新迁移将运行。

    这与您在本地使用 manage.pymigrate 进行反向迁移时没有什么不同,除非您是在远程实例上执行此操作。

    【讨论】:

      猜你喜欢
      • 2015-06-14
      • 2020-09-21
      • 2021-02-03
      • 2014-03-10
      • 1970-01-01
      • 2019-04-02
      • 2015-11-05
      • 2015-04-24
      • 2016-10-21
      相关资源
      最近更新 更多