为什么Django的ManyToManyField导致管理界面崩溃?为什么没有生成中间表?
为什么这一行
users_favorited_by = models.ManyToManyField('auth.User')
或者这一行,也会导致同样的错误:
users_favorited_by = models.ManyToManyField(User)
在这个模型中
class Album(models.Model):
OFFICIALITY = (
('J', 'Major studio release'),
('I', 'Non-major official release'),
('U', 'Unofficial'),
)
title = models.CharField(max_length=70)
description = models.TextField(max_length=500, default="", null=True, blank=True)
pub_date = models.DateField('release date')
officiality = models.CharField(max_length=1, choices=OFFICIALITY)
is_concert = models.BooleanField(default=False)
main_info_url = models.URLField(blank=False)
thumbnail = models.FileField(upload_to=get_upload_file_name, blank=True, null=True)
#virtual field to skip over the through table.
songs = models.ManyToManyField("Song", through="AlbumSong")
users_favorited_by = models.ManyToManyField('auth.User')
#Alternative to Meta.ordering [2/2]:
#objects = AlbumAscPubDateManager()
def __str__(self):
return self.title
class Meta:
#Default ordering is by release date, ascending.
ordering = ['pub_date']
在管理员界面中,点击某个专辑时会出现这个错误?
ProgrammingError at /admin/billyjoel/album/1/
relation "billyjoel_album_users_favorited_by" does not exist
LINE 1: ...LECT "auth_user"."id" FROM "auth_user" INNER JOIN "billyjoel...
^
管理员界面运行得很好,直到你点击一个专辑查看详细信息。
如果把 ManyToManyField
注释掉,运行 makemigrations
然后 migrate
,管理员界面就能正常工作——你可以看到专辑的详细信息。
根据 这个评论,错误提示意味着数据库中没有这个列。
那么为什么,当取消注释 ManyToManyField
(然后再次运行 makemigrations
和 migrate
)时,数据库表没有被创建呢?在我之前的问题中,前两个回答者都说应该会自动创建一个中间表。那么它在哪里呢?
jdb=# \dt public.*
List of relations
Schema | Name | Type | Owner
--------+----------------------------+-------+--------
public | auth_group | table | pguser
public | auth_group_permissions | table | pguser
public | auth_permission | table | pguser
public | auth_user | table | pguser
public | auth_user_groups | table | pguser
public | auth_user_user_permissions | table | pguser
public | billyjoel_album | table | pguser
public | billyjoel_albumsong | table | pguser
public | billyjoel_song | table | pguser
public | django_admin_log | table | pguser
public | django_content_type | table | pguser
public | django_migrations | table | pguser
public | django_session | table | pguser
(13 rows)
错误追踪:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8001/admin/billyjoel/album/1/
Django Version: 1.7c2
Python Version: 3.4.0
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'billyjoel')
Installed Middleware:
('django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/contrib/admin/options.py" in wrapper
546. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/contrib/admin/sites.py" in inner
204. return view(request, *args, **kwargs)
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/contrib/admin/options.py" in change_view
1416. return self.changeform_view(request, object_id, form_url, extra_context)
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapper
29. return bound_func(*args, **kwargs)
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/utils/decorators.py" in bound_func
25. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/db/transaction.py" in inner
394. return func(*args, **kwargs)
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/contrib/admin/options.py" in changeform_view
1378. form = ModelForm(instance=obj)
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/forms/models.py" in __init__
319. object_data = model_to_dict(instance, opts.fields, opts.exclude)
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/forms/models.py" in model_to_dict
149. data[f.name] = list(qs.values_list('pk', flat=True))
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/db/models/query.py" in __iter__
141. self._fetch_all()
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/db/models/query.py" in _fetch_all
964. self._result_cache = list(self.iterator())
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/db/models/query.py" in iterator
1200. for row in self.query.get_compiler(self.db).results_iter():
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/db/models/sql/compiler.py" in results_iter
699. for rows in self.execute_sql(MULTI):
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/db/models/sql/compiler.py" in execute_sql
785. cursor.execute(sql, params)
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
81. return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
65. return self.cursor.execute(sql, params)
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/db/utils.py" in __exit__
94. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/utils/six.py" in reraise
549. raise value.with_traceback(tb)
File "/home/jeffy/django_files/django_test_venv/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
65. return self.cursor.execute(sql, params)
Exception Type: ProgrammingError at /admin/billyjoel/album/1/
Exception Value: relation "billyjoel_album_users_favorited_by" does not exist
LINE 1: ...LECT "auth_user"."id" FROM "auth_user" INNER JOIN "billyjoel...
^
2 个回答
0
这是我按照@DanielRoseman的建议执行的步骤,我在我的Ubuntu机器上使用了两个命令行窗口,两个窗口都在“main”用户的命令提示符下:
- 首先,从
/home/jeffy/django_files/django_test/billyjoel/migrations
和/home/jeffy/django_files/django_test/billyjoel/migrations/__pycache__
文件夹中删除所有"000*"
文件。 - 第一个命令行窗口:
- 输入
sudo su - postgres
,切换到postgres用户。 - 在postgres的命令提示符下:
- 输入
dropdb django_test_db
,删除数据库。 - 输入
createdb django_test_db
,重新创建数据库。 - 输入
psql django_test_db
,进入数据库。 - 输入
\dt public.*
,查看表格(应该显示没有表格)。
- 输入
- 输入
- 第二个命令行窗口:
- 输入
source /home/jeffy/django_files/django_test_venv/bin/activate
,激活虚拟环境。 - 输入
cd /home/jeffy/django_files/django_test
,进入包含manage.py
的目录。 - 输入
python manage.py makemigrations
,创建迁移文件。 - 输入
python manage.py migrate
,应用迁移。
- 输入
- 回到第一个命令行窗口:
- 验证操作是否成功:
- 输入
psql django_test_db
,进入数据库。 - 输入
\dt public.*
,查看表格(应该显示你的Django表格)。
- 输入
- 验证操作是否成功:
3
我觉得你的数据库在这些注释、迁移和取消注释的操作中变得不太正常了。你可以试着完全删除你的数据库,删掉迁移文件,然后再运行一下makemigrations和migrate命令。