【问题标题】:How to add a Heroku Django app's new model table to the remote Heroku Postgres with Python migrate?如何使用 Python 迁移将 Heroku Django 应用程序的新模型表添加到远程 Heroku Postgres?
【发布时间】:2016-12-19 23:30:00
【问题描述】:

在成功完成a Heroku Python app with a Postgres db 上的教程后,我在 Heroku 应用程序上创建了一个新模型,基于现有代码,通过复制和粘贴现有模型及其表的函数和文件。 但实际上让 Heroku 在 Postgres 上远程创建表时遇到了麻烦。经过反复试验,我在下面找到了答案。

设置:Heroku Python 在本地和远程运行,Heroku Postgres 仅在远程运行。

【问题讨论】:

    标签: python django postgresql heroku


    【解决方案1】:

    我想通过运行本教程中使用的heroku run python manage.py migrate,在我的远程 Heroku Postgres 数据库上实际创建我的新表。但它并没有立即奏效。我需要做的是设置几个 Python 文件,然后在最后运行该命令。

    如果您也编辑模型(例如添加新字段),这也有效。

    我添加的所有文件都在基于this tutorialHeroku tutorial's code

    这正是我所做的:

    1. hello/models.py,添加

      class Mytable(models.Model):
          when = models.DateTimeField('date created', auto_now_add=True)
      
    2. 通过在我的 Mac 终端(已登录 Heroku 和 virtualenv)上运行以下命令,让 Python 在我的本地 hello/migrations 中生成 0002_mytable.py 文件:

      python manage.py makemigrations hello
      

      我收到了这样的回复:

      Migrations for 'hello':
        0002_mytable.py:
          - Create model Mytable
      
    3. 将这个新的迁移文件添加到我的远程 Heroku

      git add hello/migrations/0002_mytable.py
      git commit -am "added new migration file"
      git push heroku master
      
    4. 让 Heroku 在远程 Heroku Postgres 上远程创建表

      heroku run python manage.py migrate
      

      你应该看到

      Running python manage.py migrate on ⬢ your-heroku-url... up, run.1699
      Operations to perform:
        Apply all migrations: admin, contenttypes, hello, sessions, auth
      Running migrations:
        Rendering model states... DONE
        Applying hello.0002_mytable... OK
      

    【讨论】:

      【解决方案2】:

      确保您已在本地进行数据库迁移

      python manage.py makemigrations
      python manage.py migrate
      git add .
      git commit -m "Database migrations"
      

      然后在您的 Procfile 中添加以下行作为第一行

      release: python manage.py migrate
      

      再次在 heroku 上部署此更改

      git add Procfile
      git commit -m "Add Release Phase to Procfile"
      git push heroku master
      

      完成....

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-23
        • 2016-09-05
        • 1970-01-01
        • 1970-01-01
        • 2016-10-07
        • 2013-09-22
        • 2018-11-05
        • 2012-04-26
        相关资源
        最近更新 更多