【发布时间】:2016-03-25 18:56:11
【问题描述】:
我目前正在从事 Django 项目。在里面我有一个应用程序'篮球'。该应用程序具有“团队”、“玩家”等模型。我已将我的项目放在 Heroku 上。
我的问题是我只能通过 Django ORM 访问“篮球”模型中的数据。当我使用原始 SQL 数据库时,看不到我的表。
举个例子,当我在 Heroku 上使用我的项目的 Django shell 时
:~/$ heroku run python3 manage.py shell
>>> from Basketball.models import Player
>>> players = Player.objects.all()
变量“玩家”确实包含“玩家”模型的所有实例。当我通过 Heroku 命令行探索数据库时
:~/$ heroku pg:psql
当我列出所有表格时
my_project::DATABASE=> \dt
我得到以下输出:
List of relations
Schema | Name | Type | Owner
--------+----------------------------+-------+----------------
public | Basketball_contract | table | **************
public | Basketball_match | table | **************
public | Basketball_matchstats | table | **************
public | Basketball_player | table | **************
public | Basketball_roster | table | **************
public | Basketball_team | table | **************
public | auth_group | table | **************
public | auth_group_permissions | table | **************
public | auth_permission | table | **************
public | auth_user | table | **************
public | auth_user_groups | table | **************
public | auth_user_user_permissions | table | **************
public | django_admin_log | table | **************
public | django_content_type | table | **************
public | django_migrations | table | **************
public | django_session | table | **************
public | postman_message | table | **************
但是当我尝试执行时
my_project::DATABASE=> SELECT * FROM Basketball_player;
我明白了
ERROR: relation "basketball_player" does not exist
LINE 1: SELECT * FROM Basketball_player;
当我在 Heroku 上对我的项目进行迁移时
:~/$ heroku run python3 manage.py makemigrations
它会进行一些迁移
Migrations for 'Basketball':
0001_initial.py:
- Create model Contract
- Create model Match
- Create model MatchStats
- Create model Player
- Create model Roster
- Create model Team
- Add field team to roster
- Add field player to matchstats
- Add field away to match
- Add field home to match
- Add field player_signed to contract
- Add field team to contract
但是当我尝试应用它们时
:~/$ heroku run python3 manage.py migrate
消息显示
Operations to perform:
Synchronize unmigrated apps: staticfiles, mathfilters, django_countries, messages
Apply all migrations: auth, sessions, admin, contenttypes, postman
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
No migrations to apply.
Your models have changes that are not yet reflected in a migration, and so won't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
【问题讨论】:
-
您不得在 Heroku 上运行 makemigrations。在本地执行,提交到 git,然后推送到 Heroku,然后运行迁移。
-
@DanielRoseman 感谢您的评论。但是 makemigrations 命令不会在数据库中应用更改吗?我的意思是我在本地有不同的数据库,在 Heroku 上有不同的数据库。
-
没有。
makemigrations在磁盘上创建迁移文件以使用migrate运行。但是在 Heroku 上,磁盘是短暂的,文件在运行之间不会持久存在。正如我所说,您必须在本地创建迁移文件并在运行迁移之前上传到 Heroku。 -
当然,你是对的。我在写
makemigrations,同时在想migrate。谢谢!
标签: python django postgresql heroku