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

时间:2014-08-21 20:35:25

标签: python django postgresql

为什么这一行

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,以及管理界面正常运行 - 您可以看到相册的详细信息。

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

为什么,当 取消 - 评论ManyToManyField(并再次运行makemigrations然后migrate)时,为什么正在创建数据库表?与我的previous question一样,前两个回答者都声明应该制作一个自动创建的直通表。那它在哪里?

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 :(得分:3)

我认为通过所有这些评论/迁移/取消注释,您的数据库处于不一致状态。尝试完全删除数据库,删除迁移文件,运行makemigrations并再次迁移。

答案 1 :(得分:0)

这就是我执行@DanielRoseman的建议,使用两个shell到我的Ubuntu机器,两者都是从" main"用户的命令提示符:

  1. 首先,删除"000*"/home/jeffy/django_files/django_test/billyjoel/migrations
  2. 中的所有/home/jeffy/django_files/django_test/billyjoel/migrations/__pycache__个文件
  3. 壳牌之一
    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 表格)
  4. 壳牌二
    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
  5. 壳牌一:
    1. 验证是否有效
      1. psql django_test_db
      2. \dt public.*(应显示您的Django表)