首页 文章

如何使用Python迁移将Heroku Django应用程序的新模型表添加到远程Heroku Postgres?

提问于
浏览
1

在成功完成a Heroku Python app with a Postgres db的教程之后,我基于现有代码在我的Heroku应用程序上创建了一个新模型,通过复制和粘贴现有模型及其表的函数和文件 . But I had trouble to actually let Heroku create the table on Postgres remotely. 经过一些反复试验后,我找到了以下答案 .

设置:Heroku Python在本地和远程运行,Heroku Postgres只能远程运行 .

1 回答

  • 3

    我想在我的远程Heroku Postgres数据库中创建我的新表,方法是运行本教程中使用的 heroku run python manage.py migrate . 但它并没有立即起作用 . 我需要做的是设置一些Python文件,然后在最后运行该命令 .

    如果您也编辑模型,例如添加新字段,则此方法有效 .

    我添加的所有文件都基于this tutorial进入Heroku tutorial's code

    这正是我所做的:

    _109_在hello/models.py中,添加

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

    我收到了这个回复:

    Migrations for 'hello':
      0002_mytable.py:
        - Create model Mytable
    
    • 将此新迁移文件添加到我的远程Heroku
    git add hello/migrations/0002_mytable.py
    git commit -am "added new migration file"
    git push heroku master
    
    • 让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
    

相关问题