django.db.utils.ProgrammingError:关系“ APP_profile”的列“ role”不存在

时间:2019-07-03 02:37:42

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

当前,我在尝试执行命令时遇到上述错误

python3 manage.py migrate

我无法弄清楚问题所在,Stackoverflow上的帖子建议删除迁移并重新创建迁移,我做到了。但是我仍然面临同样的问题。

请在下面找到一些代码:

models.py:

from __future__ import unicode_literals
from django.db import models
from bokeh.themes import default
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import AbstractUser
from django.utils import timezone

# Create your models here.
class Project(models.Model):
    REQUEST_STATUS = (
        ('Pending', 'Pending'),
        ('Approved', 'Approved'),
        ('Denied', 'Denied'),
    )

    form_type = models.CharField(max_length=20, blank=False, null=False)
    created_at = models.DateTimeField(default=timezone.now())
    status = models.CharField(max_length=20, choices=REQUEST_STATUS, default='Pending')
    user = models.ForeignKey(User, on_delete=models.CASCADE)

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

class Profile(models.Model):
    NORMAL = 1
    APPROVER = 2
    REVIEWER = 3
    ROLE_CHOICES = (
        (NORMAL, 'Normal'),
        (APPROVER, 'Approver'),
        (REVIEWER, 'Reviewer'),
    )
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, null=True, blank=True)   
    def __str__(self):  # __unicode__ for Python 2
        return self.user.username


@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    instance.profile.save()

admin.py:

from django.contrib import admin

# Register your models here.
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

from .models import Profile, Project

admin.AdminSite.site_url = '/MyProject'
class ProfileInline(admin.StackedInline):
    model = Profile
    can_delete = False
    verbose_name_plural = 'Sites'
    fk_name = 'user'


class CustomUserAdmin(UserAdmin):
    inlines = (ProfileInline, )
    list_display = ('id', 'username', 'email', 'first_name', 'last_name', 'is_staff', 'get_role')
    list_select_related = ('profile', )

    def get_role(self, instance):
        return instance.profile.role
    get_role.short_description = 'Role'

    def get_inline_instances(self, request, obj=None):
        if not obj:
            return list()
        return super(CustomUserAdmin, self).get_inline_instances(request, obj)


admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

admin.site.register(Project)

urls.py:

from django.contrib import admin
from django.urls import path, include, re_path
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('APP.urls')),
    re_path(r'^APP/admin/', admin.site.urls, name='admin'),
    re_path(r'^logoutview/admin/', admin.site.urls, name='admin'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

settings.py:

....
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases

DATABASES = {
    #'default': {
        #'ENGINE': 'django.db.backends.sqlite3',
        #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    #}
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'app_db',
        'HOST': '/Applications/djangostack-2.0.2-3/postgresql',
        'PORT': '5432',
        'USER': 'app_user',
       'PASSWORD': '**********'
    }
}
....

这是我的追踪记录:

File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: column "role" does not exist
LINE 1: ...l_profile" ALTER COLUMN "role" TYPE integer USING "role"::in...
                                                             ^


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 "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/core/management/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/core/management/base.py", line 335, in execute
    output = self.handle(*args, **options)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/core/management/commands/migrate.py", line 200, in handle
    fake_initial=fake_initial,
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/migrations/executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/migrations/executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/migrations/migration.py", line 122, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/migrations/operations/fields.py", line 216, in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/backends/base/schema.py", line 509, in alter_field
    old_db_params, new_db_params, strict)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/backends/postgresql/schema.py", line 122, in _alter_field
    new_db_params, strict,
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/backends/base/schema.py", line 650, in _alter_field
    params,
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/backends/base/schema.py", line 117, in execute
    cursor.execute(sql, params)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/backends/utils.py", line 100, in execute
    return super().execute(sql, params)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/backends/utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/backends/utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: column "role" does not exist
LINE 1: ...l_profile" ALTER COLUMN "role" TYPE integer USING "role"::in...
                                                            ^

任何帮助或建议将不胜感激!我将非常乐意提供所需的任何其他代码或信息。预先感谢您提供的所有支持和帮助。

此致

Amey Kelekar

2 个答案:

答案 0 :(得分:1)

首次登录postgres dayabase并选择app_db 然后从django_migrations中删除与role列相关的一行。

分别运行makemigrationsmigrate命令。

答案 1 :(得分:0)

您可能在同一应用程序下仍然存在相同的错误,并且有多个未应用的迁移。那样的话;

yourApp$./manage.py makemigrations
yourApp$./manage.py showmigrations
# delete unapplied migrations indicated by empty [] before name of the file
yourApp$./manage.py migrate --fake

完成此操作后,该应用程序似乎可以正常运行,但数据库中可能仍不存在该列。当您尝试对数据库执行POST时,您可能会意识到这一点。如果再次出现错误,请从代码中的 migrations文件夹和数据库中的 django_migrations表删除与角色有关的迁移,然后做迁移->迁移

yourComp$sudo -u postgres psql
postgres=#\c yourdb_name;
your_db=#select * from django_migrations;
# identify the id of the migration affecting 'role' column
your_db=#delete from django_migrations where id=3;
your_db=#delete from django_migrations where id=4;

从代码中删除相同的迁移并执行;

 (venv)yourApp$./manage.py makemigrations appname
 (venv)youApp$./manage.py migrate appname