django.db.utils.ProgrammingError:关系“ auth_permission”不存在

时间:2018-10-23 11:16:02

标签: django python-3.x django-models

我的本​​地环境中有一个有效的sqlite数据库。在heroku上,我正在使用psql。但是尝试运行

时出现以下错误
$ heroku run python manage.py migrate
Traceback (most recent call last):
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "auth_permission" does not exist
LINE 1: ...ntent_type_id", "auth_permission"."codename" FROM "auth_perm...
                                                             ^


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 350, in execute
    self.check()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 379, in check
    include_deployment_checks=include_deployment_checks,
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 366, in _run_checks
    return checks.run_checks(**kwargs)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/checks/registry.py", line 71, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
    all_namespaces = _load_all_namespaces(resolver)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
    url_patterns = getattr(resolver, 'url_patterns', [])
  File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/urls/resolvers.py", line 533, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/urls/resolvers.py", line 526, in urlconf_module
    return import_module(self.urlconf_name)
  File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/app/codeTrial/urls.py", line 20, in <module>
    path('', include('coderunner.urls')),
  File "/app/.heroku/python/lib/python3.6/site-packages/django/urls/conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
  File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/app/coderunner/urls.py", line 4, in <module>
    from . import views
  File "/app/coderunner/views.py", line 34, in <module>
    'perm_obj': Permission.objects.get(name='Can add Questions'),
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 393, in get
    num = len(clone)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 250, in __len__
    self._fetch_all()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 54, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1065, in execute_sql
    cursor.execute(sql, params)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "auth_permission" does not exist
LINE 1: ...ntent_type_id", "auth_permission"."codename" FROM "auth_perm...
                                                             ^

我猜这在heroku上使用psql并不是问题,因为当我尝试将同一应用程序复制到另一台Linux机器上并尝试重新创建sqlite数据库时,它会提供sqlite3.OperationalError: no such table: auth_permission

当我从app / migration文件夹中删除所有14个迁移文件后尝试迁移时,会发生相同的错误。

我不明白为什么至少没有创建Django数据库表。是不是由于app / models.py文件中的任何错误?

如果您需要查看我的models.py文件,则为:

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.validators import MinValueValidator


# Create your models here.
class Questions(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    published_on = models.DateTimeField(auto_now_add=True)
    question_text = models.CharField(max_length=200)
    question_desc = models.CharField(max_length=500)
    pre_code_snippet = models.TextField()
    output_format = models.CharField(max_length=500)
    timeout = models.IntegerField(default=5, validators=[MinValueValidator(0)])
    run_testcase1_input = models.TextField(max_length=50)
    run_testcase1_output = models.TextField()
    submit_testcase1_input = models.TextField(max_length=50)
    submit_testcase1_output = models.TextField()
    submit_testcase2_input = models.TextField(max_length=50)
    submit_testcase2_output = models.TextField()
    times_submitted = models.IntegerField(default=0)
    times_correct = models.IntegerField(default=0)
    times_wrong = models.IntegerField(default=0)
    score = models.IntegerField(default=10,
                                validators=[MinValueValidator(5)])

    class Meta:
        verbose_name = 'Questions'
        verbose_name_plural = 'Questions'

    def __str__(self):
        return self.question_text


class Submissions(models.Model):
    username = models.ForeignKey(User, on_delete=models.CASCADE)
    submitted_on = models.DateTimeField(auto_now_add=True)
    submitted_snippet = models.TextField()
    question = models.ForeignKey(Questions, on_delete=models.CASCADE)

    class Meta:
        verbose_name = 'Submissions'
        verbose_name_plural = 'Submissions'

    def __str__(self):
        return (str(self.username) + '@ [' + str(self.question) + ']')


class UserProfile(models.Model):
    username = models.OneToOneField(User, on_delete=models.CASCADE)
    score = models.IntegerField(default=0,
                                validators=[MinValueValidator(0)])

    class Meta:
        verbose_name = "UserProfile"
        verbose_name_plural = "UserProfiles"

    def __str__(self):
        return str(self.username)


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(username=instance)


@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.userprofile.save()

project / settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'coderunner.apps.CoderunnerConfig',
]

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

db_from_env = dj_database_url.config()
DATABASES['default'].update(db_from_env)

我正在使用Django_2.1.2。我尚未找到任何适合此问题的解决方案。让我知道是否需要提供其他信息。 如果您需要完整的源代码,这是我的Github link

2 个答案:

答案 0 :(得分:0)

是的,我发现了问题。即使在将问题发布到这里之后,我仍在寻找确切的问题,但我还是找到了一篇相关文章,其中有人评论说,根据追溯日志,他的form.py文件存在问题。因此,我认为就我的情况而言,除了我的可疑文件(例如models.py,settings.py或迁移文件)之外,其他文件中可能还会存在一些问题。所以我再次检查了回溯,发现了这个……

File "/app/codeTrial/urls.py", line 20, in <module> path('', include('coderunner.urls')),

最终执行 coderunner / urls.py ,我在其中导入 coderunner / views.py 内容。

File "/app/coderunner/urls.py", line 4, in <module>
    from . import views

coderunner / views.py 中,我实际上试图在任何视图函数/类之外创建 Permission 类的对象。因此,当从url.py导入views.py时,views.py被执行。这意味着它甚至在创建之前就已访问 auth 模型,这实际上引发了异常auth_permission does not exist。因此,我在views.py中处理了该代码,然后尝试再次迁移... Boom!成功迁移。

在我的开发环境中,迁移没有问题,因为 auth 模型是在我在coderunner / views.py中实现未处理的代码时创建的。

答案 1 :(得分:0)

  1. 您必须评论所有应用的根 URL 路由
  2. 从 INSTALLED_APPS 列表中评论您的应用
  3. 运行python manage.py migrate。它将迁移 Django 本身的初始迁移。
  4. 现在取消注释您在前两个步骤中所做的所有评论