(Django Migration Bug with PostgreSQL) django.db.utils.ProgrammingError: 关系“subjects_subject”不存在

问题描述

**将 github 链接到此存储库:**https://github.com/thetruefuss/elmer

当我使用sqlite作为数据库启动这个项目时,它与数据库完美迁移,但是当我将其切换到POSTGRESQL时,出现此错误:

django.db.utils.ProgrammingError: relation "subjects_subject" does not exist
LINE 1: ...ect"."created","subjects_subject"."updated" FROM "subjects_...

重点是:在这个 repo 中它已经有所有模型的所有迁移文件,你可以检查这个 repo,我不能用 pgadmin 4 中的数据库迁移它

db settings.py

    DATABASES = {
      'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2','NAME': 'demo_postgres','USER':'postgres','PASSWORD':'18092000','PORT':'5432','HOST':'127.0.0.1',}
    }

** 我的命令 **

python manage.py migrate

subjects_subject (migration_file)


    class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),('boards','0001_initial'),]

    operations = [
        migrations.CreateModel(
            name='Subject',fields=[
                ('id',models.AutoField(auto_created=True,primary_key=True,serialize=False,verbose_name='ID')),('title',models.CharField(db_index=True,max_length=150)),('slug',models.SlugField(blank=True,max_length=150,null=True)),('body',models.TextField(blank=True,max_length=5000,('photo',models.ImageField(blank=True,null=True,upload_to='subject_photos/',verbose_name='Add image (optional)')),('rank_score',models.FloatField(default=0.0)),('active',models.BooleanField(default=True)),('created',models.DateTimeField(default=django.utils.timezone.now)),('updated',models.DateTimeField(auto_now=True)),('author',models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,related_name='posted_subjects',to=settings.AUTH_USER_MODEL)),('board',related_name='submitted_subjects',to='boards.Board')),('mentioned',models.ManyToManyField(blank=True,related_name='m_in_subjects',('points',related_name='liked_subjects',],options={
                'ordering': ('-created',),},]

subjects_subject(model_file)

    class Subject(models.Model):
    """
    Model that represents a subject.
    """
    title = models.CharField(max_length=150,db_index=True)
    slug = models.SlugField(max_length=150,blank=True)
    body = models.TextField(max_length=5000,blank=True,null=True)
    photo = models.ImageField(
        upload_to='subject_photos/',verbose_name=u"Add image (optional)",null=True
    )
    author = models.ForeignKey(User,on_delete=models.CASCADE)
    board = models.ForeignKey(Board,on_delete=models.CASCADE)
    points = models.ManyToManyField(
        settings.AUTH_USER_MODEL,blank=True
    )
    mentioned = models.ManyToManyField(
        User,blank=True
    )
    rank_score = models.FloatField(default=0.0)
    active = models.BooleanField(default=True)
    created = models.DateTimeField(default=timezone.now)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('-created',)

编辑:1(完整追溯)

 File "E:\Python\elmer\manage.py",line 15,in <module>
   execute_from_command_line(sys.argv)
 File "E:\Python\elmer\venv\lib\site-packages\django\core\management\__init__.py",line 381,in execute_from_command_line
   utility.execute()
 File "E:\Python\elmer\venv\lib\site-packages\django\core\management\__init__.py",line 375,in execute
   self.fetch_command(subcommand).run_from_argv(self.argv)
 File "E:\Python\elmer\venv\lib\site-packages\django\core\management\base.py",line 316,in run_from_argv
   self.execute(*args,**cmd_options)
 File "E:\Python\elmer\venv\lib\site-packages\django\core\management\base.py",line 350,in execute
   self.check()
 File "E:\Python\elmer\venv\lib\site-packages\django\core\management\base.py",line 376,in check
   all_issues = self._run_checks(
 File "E:\Python\elmer\venv\lib\site-packages\django\core\management\commands\migrate.py",line 60,in _run_checks
   issues.extend(super()._run_checks(**kwargs))
 File "E:\Python\elmer\venv\lib\site-packages\django\core\management\base.py",line 366,in _run_checks
   return checks.run_checks(**kwargs)
 File "E:\Python\elmer\venv\lib\site-packages\django\core\checks\registry.py",line 71,in run_checks
   new_errors = check(app_configs=app_configs)
 File "E:\Python\elmer\venv\lib\site-packages\django\core\checks\urls.py",line 13,in check_url_config
   return check_resolver(resolver)
 File "E:\Python\elmer\venv\lib\site-packages\django\core\checks\urls.py",line 23,in check_resolver
   return check_method()
 File "E:\Python\elmer\venv\lib\site-packages\django\urls\resolvers.py",line 396,in check
   for pattern in self.url_patterns:
 File "E:\Python\elmer\venv\lib\site-packages\django\utils\functional.py",line 37,in __get__
   res = instance.__dict__[self.name] = self.func(instance)
 File "E:\Python\elmer\venv\lib\site-packages\django\urls\resolvers.py",line 533,in url_patterns
   patterns = getattr(self.urlconf_module,"urlpatterns",self.urlconf_module)
 File "E:\Python\elmer\venv\lib\site-packages\django\utils\functional.py",line 526,in urlconf_module
   return import_module(self.urlconf_name)
 File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.496.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py",line 127,in import_module
   return _bootstrap._gcd_import(name[level:],package,level)
 File "<frozen importlib._bootstrap>",line 1030,in _gcd_import
 File "<frozen importlib._bootstrap>",line 1007,in _find_and_load
 File "<frozen importlib._bootstrap>",line 986,in _find_and_load_unlocked
 File "<frozen importlib._bootstrap>",line 680,in _load_unlocked
 File "<frozen importlib._bootstrap_external>",line 790,in exec_module
 File "<frozen importlib._bootstrap>",line 228,in _call_with_frames_removed
 File "E:\Python\elmer\mysite\urls.py",line 33,in <module>
   import subjects.views as subjects_views
 File "E:\Python\elmer\subjects\views.py",line 58,in <module>
   class TrendingPageView(ListView):
 File "E:\Python\elmer\subjects\views.py",line 63,in TrendingPageView
   queryset = get_trending_subjects()
 File "E:\Python\elmer\subjects\views.py",line 25,in get_trending_subjects
   for subject in subjects:
 File "E:\Python\elmer\venv\lib\site-packages\django\db\models\query.py",line 268,in __iter__
   self._fetch_all()
 File "E:\Python\elmer\venv\lib\site-packages\django\db\models\query.py",line 1186,in _fetch_all
   self._result_cache = list(self._iterable_class(self))
 File "E:\Python\elmer\venv\lib\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 "E:\Python\elmer\venv\lib\site-packages\django\db\models\sql\compiler.py",line 1065,in execute_sql
   cursor.execute(sql,params)
 File "E:\Python\elmer\venv\lib\site-packages\django\db\backends\utils.py",line 100,in execute
   return super().execute(sql,line 68,in execute
   return self._execute_with_wrappers(sql,params,many=False,executor=self._execute)
 File "E:\Python\elmer\venv\lib\site-packages\django\db\backends\utils.py",line 77,in _execute_with_wrappers
   return executor(sql,many,context)
 File "E:\Python\elmer\venv\lib\site-packages\django\db\backends\utils.py",line 85,in _execute
   return self.cursor.execute(sql,params)
 File "E:\Python\elmer\venv\lib\site-packages\django\db\utils.py",line 89,in __exit__
   raise dj_exc_value.with_traceback(traceback) from exc_value
 File "E:\Python\elmer\venv\lib\site-packages\django\db\backends\utils.py",params)
django.db.utils.ProgrammingError: relation "subjects_subject" does not exist
LINE 1: ...ect"."created","subjects_subject"."updated" FROM "subjects_...
                                                            ^

解决方法

您的问题是您在应用启动时执行数据库查询,这会导致很多迁移问题,通常不鼓励使用。

在您调用的 TrendingPageView 类的主体中,get_trending_subjects() 正在对 Subject 模型执行查询,您需要将其移动到一个方法中,以便它不被调用在启动时但在访问视图时。

class TrendingPageView(ListView):
    model = Subject
    paginate_by = 15
    template_name = 'subjects/trending.html'
    context_object_name = 'subjects'

    def get_queryset(self):
        return get_trending_subjects()

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...