运行 make 迁移时出现 Django 关系错误

Posted

技术标签:

【中文标题】运行 make 迁移时出现 Django 关系错误【英文标题】:Django relation error when running make migrations 【发布时间】:2016-12-29 06:15:19 【问题描述】:

嘿,我正在尝试初始化一个新数据库,但在设置迁移时遇到了一些问题。我得到的错误似乎源于设置我的表格。在我使用的表单中,我正在创建一个选择字段:

from django import forms
from ..custom_admin import widgets, choices


class MemberForm(forms.Form):
    provinces = forms.ChoiceField(label='Provinces', choices=choices.PROVINCE_CHOICES, required=True)

PROVINCE_CHOICES 来自这里:

from ..base.models import ProvinceCode

PROVINCE_CHOICES = []
for province in ProvinceCode.objects.filter(country_code_id=1).order_by('code'):
    PROVINCE_CHOICES.append((province.code, province.code))

问题似乎是在迁移发生之前调用了这个循环,给我一个错误,指出省模型不存在。注释掉对该文件的引用允许迁移工作,但是,这似乎是继续使用的不切实际的解决方案。有没有办法绕过这个错误?

作为参考,这是我运行manage.py makemigrations时遇到的错误:

./manage.py makemigrations        
Traceback (most recent call last):
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "pc_psr_code" does not exist
LINE 1: ...escription", "pc_psr_code"."country_code_id" FROM "pc_psr_co...
                                                             ^


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

Traceback (most recent call last):
  File "./manage.py", line 9, in <module>
    django.setup()
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/django/apps/registry.py", line 115, in populate
    app_config.ready()
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/debug_toolbar/apps.py", line 15, in ready
    dt_settings.patch_all()
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/debug_toolbar/settings.py", line 228, in patch_all
    patch_root_urlconf()
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/debug_toolbar/settings.py", line 216, in patch_root_urlconf
    reverse('djdt:render_panel')
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/django/core/urlresolvers.py", line 568, in reverse
    app_list = resolver.app_dict[ns]
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/django/core/urlresolvers.py", line 360, in app_dict
    self._populate()
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/django/core/urlresolvers.py", line 293, in _populate
    for pattern in reversed(self.url_patterns):
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/django/utils/functional.py", line 33, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/django/core/urlresolvers.py", line 417, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/django/utils/functional.py", line 33, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module
    return import_module(self.urlconf_name)
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 662, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/Users/js/Documents/app/platform/test/pc/urls.py", line 7, in <module>
    from .custom_admin import urls as custom_urls
  File "/Users/js/Documents/app/platform/test/pc/custom_admin/urls.py", line 3, in <module>
    from ..party import views as party_views
  File "/Users/js/Documents/app/platform/test/pc/party/views.py", line 1, in <module>
    from ..party import forms
  File "/Users/js/Documents/app/platform/test/pc/party/forms.py", line 2, in <module>
    from ..custom_admin import widgets, choices
  File "/Users/js/Documents/app/platform/test/pc/custom_admin/choices.py", line 9, in <module>
    for province in ProvinceCode.objects.filter(country_code_id=1).order_by('code'):
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/django/db/models/query.py", line 258, in __iter__
    self._fetch_all()
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/django/db/models/query.py", line 1074, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/django/db/models/query.py", line 52, in __iter__
    results = compiler.execute_sql()
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 848, in execute_sql
    cursor.execute(sql, params)
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/django/db/utils.py", line 95, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "pc_psr_code" does not exist
LINE 1: ...escription", "pc_psr_code"."country_code_id" FROM "pc_psr_co...

省模式:

class ProvinceCode(models.Model):
    code = models.CharField(blank=False, null=False, unique=True)
    country_code = models.ForeignKey('CountryCode', blank=False, null=True)

【问题讨论】:

您能否展示您的models.py,特别是与makemigrations 试图更改的表关联的模型? 它没有尝试更改模型,我正在初始化一个新数据库,因此数据库中没有任何内容。但我也会发布该模型 好的。只是涵盖了这里的所有基础,您的 BaseCodeModel 继承自 django.db models.Model 对吗?我对抛出的错误有点困惑,因为理论上如果这是数据库的初始创建,我不明白为什么“FROM”关键字会出现在任何正在创建的查询中。有理由认为只有“创建表”调用对吗?有没有办法让你得到比小 sn-p manage.py 向你抛出的更详细的错误? 是的,抱歉,应该也包含该模型,但它确实继承自 models.Model。但这不是问题,如果我删除对该文件的引用,一切正常,包括该模型的所有其他用途。据我所知,这是我能找到的最完整的错误。问题是填充 PROVINCE_CHOICES 的 for 循环在数据库初始化之前正在运行,但我不知道如何更改此顺序 您的 PROVINCE_CHOICES 初始化位于哪个文件中?除非它在模型中,否则它不应该对 makemigrations 调用产生任何影响。 【参考方案1】:

您无法在应用注册表初始化期间执行查询。这段时间你的choices.py文件被间接导入,导致报错。要解决此问题,您可以将 callable 传递给 choices

def get_provinces():
    province_choices = []
    for province in ProvinceCode.objects.filter(country_code_id=1).order_by('code'):
        province_choices.append((province.code, province.code))
    return province_choices

class MemberForm(forms.Form):
    provinces = forms.ChoiceField(label='Provinces', choices=get_provinces, required=True)

【讨论】:

get_provinces函数中是否缺少return? @knbk 你能看看这个吗? ***.com/questions/61245569/…

以上是关于运行 make 迁移时出现 Django 关系错误的主要内容,如果未能解决你的问题,请参考以下文章

在 Heroku 上部署时出现 Django 1.7 迁移错误

Django 2.0.7 - 进行重命名字段迁移时出现语法错误

使用查询数据库的默认字段函数迁移时出现 Django 错误

运行“vue 升级”时出现“无法解决依赖关系”错误

恢复 Django-mailer 数据库时出现 MySQL 错误 1118(行大小太大)

运行时出现 Docker 错误:没有名为“pytz”的模块