为什么Django的ManyToManyField导致管理界面崩溃?为什么没有创建一个通过表?

2024-09-28 22:04:41 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么是这条线

users_favorited_by = models.ManyToManyField('auth.User')

或者这一个也会导致同样的错误:

^{pr2}$

在这个模型中

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,管理界面工作良好——您可以看到专辑的详细信息。在

根据this comment,错误意味着数据库中不存在该列。在

那么,当un-注释掉ManyToManyField(再次运行makemigrations,然后migrate)时,为什么没有创建数据库表呢?就像在我的previous question中一样,前两个答案都声明应该创建一个自动创建的through表。它在哪里?在

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...
                                                             ^

Tags: djangoinpytestselfauthhomevenv
2条回答

这就是我如何执行@DanielRoseman的建议,在我的Ubuntu机器上使用两个shell,都是从“main”用户的命令提示符开始的:

  1. 首先,删除/home/jeffy/django_files/django_test/billyjoel/migrations/home/jeffy/django_files/django_test/billyjoel/migrations/__pycache__中的所有"000*"文件
  2. 壳牌一号
    1. sudo su - postgres
    2. postgres命令提示符:
      1. dropdb django_test_db
      2. createdb django_test_db
      3. psql django_test_db
      4. \dt public.*(应显示no表)
  3. 炮弹二号
    1. source /home/jeffy/django_files/django_test_venv/bin/activate
    2. cd /home/jeffy/django_files/django_test(包含manage.py的目录)
    3. python manage.py makemigrations
    4. python manage.py migrate
  4. 壳牌一号:
    1. 验证它与
      1. psql django_test_db
      2. \dt public.*(应该显示Django表)

正在通过不一致的注释状态迁移数据库。尝试完全删除数据库,删除迁移文件,然后运行makemigrations并再次迁移。在

相关问题 更多 >