简体   繁体   中英

How to add a Heroku Django app's new model table to the remote Heroku Postgres with Python migrate?

After successfully finishing a tutorial on a Heroku Python app with a Postgres db , I made a new model on my Heroku app, based on the existing code, by copying and pasting the existing model and its table's functions and files. But I had trouble to actually let Heroku create the table on Postgres remotely. After some trial-and-error, I found the answer below.

Setup: Heroku Python is running locally and remotely, Heroku Postgres is only running remotely.

I wanted to actually create my new table on my remote Heroku Postgres database, by running heroku run python manage.py migrate , which was used in the tutorial. But it didn't work right off the bat. What I needed to do was to set up a few Python files and then run that command at the end.

This works if you edit the model too, such as adding a new field.

All the files I added are into the Heroku tutorial's code based on this tutorial

This is exactly what I did:

  1. in hello/models.py , add

     class Mytable(models.Model): when = models.DateTimeField('date created', auto_now_add=True) 
  2. Let Python generate the 0002_mytable.py file in my local hello/migrations by running the following command on my Mac terminal (which was logged into Heroku and in the virtualenv):

     python manage.py makemigrations hello 

    and I got this response:

     Migrations for 'hello': 0002_mytable.py: - Create model Mytable 
  3. Add this new migrations file to my remote Heroku

     git add hello/migrations/0002_mytable.py git commit -am "added new migration file" git push heroku master 
  4. Let Heroku create the table remotely on the remote Heroku Postgres

     heroku run python manage.py migrate 

    you should see

     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 

Ensure that you have made your database migrations locally

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

Then add the below line as first in your Procfile

release: python manage.py migrate

Again deploy this changes on heroku

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

Done....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM