当前位置:  开发笔记 > 编程语言 > 正文

删除迁移和makemigrations后的django.db.utils.OperationalError

如何解决《删除迁移和makemigrations后的django.db.utils.OperationalError》经验,为你挑选了1个好方法。

我删除了项目中的所有迁移,删除了数据库并尝试使用manage.py makemigrations命令重新创建迁移.但是我收到了错误:

Traceback (most recent call last):
  File "/Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py", line 41, in 
    run_module(manage_file, None, '__main__', True)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 176, in run_module
    fname, loader, pkg_name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 82, in _run_module_code
    mod_name, mod_fname, mod_loader, pkg_name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/Users/rankor/src/python/web/Auction/Auction/manage.py", line 10, in 
    execute_from_command_line(sys.argv)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
    utility.execute()
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/management/__init__.py", line 342, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/management/base.py", line 398, in execute
    self.check()
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check
    include_deployment_checks=include_deployment_checks,
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/checks/urls.py", line 10, in check_url_config
    return check_resolver(resolver)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/checks/urls.py", line 19, in check_resolver
    for pattern in resolver.url_patterns:
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module
    return import_module(self.urlconf_name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/rankor/src/python/web/Auction/Auction/Auction/urls.py", line 14, in 
    url(r'^orders/', include('orders.urls', namespace='orders')),
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 52, in include
    urlconf_module = import_module(urlconf_module)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/rankor/src/python/web/Auction/Auction/orders/urls.py", line 3, in 
    from orders.views import CreateOrderView, OrdersView, OrderView
  File "/Users/rankor/src/python/web/Auction/Auction/orders/views.py", line 7, in 
    from orders.forms import OrderForm
  File "/Users/rankor/src/python/web/Auction/Auction/orders/forms.py", line 47, in 
    class OrderForm(ModelForm):
  File "/Users/rankor/src/python/web/Auction/Auction/orders/forms.py", line 60, in OrderForm
    widget=forms.Select, queryset=OrderCategory.objects.filter(parent__isnull=False).order_by('ordering'))
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/forms/models.py", line 1142, in __init__
    self.queryset = queryset
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/forms/models.py", line 1168, in _set_queryset
    self.widget.choices = self.choices
  File "/Users/rankor/src/python/web/Auction/Auction/orders/forms.py", line 16, in _get_choices
    if not self.queryset:
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/models/query.py", line 266, in __nonzero__
    return type(self).__bool__(self)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/models/query.py", line 262, in __bool__
    self._fetch_all()
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/models/query.py", line 1074, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/models/query.py", line 52, in __iter__
    results = compiler.execute_sql()
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 852, in execute_sql
    cursor.execute(sql, params)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 323, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: orders_ordercategory

订单:

class OrderForm(ModelForm):
    """
    Order form
    """

    class Meta:
        model = Order
        fields = ('city', 'category', 'title', 'min_price', 'max_price', 'description', 'delivery_type', 'valid_to')

    city = forms.ModelChoiceField(
            widget=forms.Select, queryset=City.objects.filter(country__code='RU').order_by('name'))

    category = CategoryChoiceField(
            widget=forms.Select, queryset=OrderCategory.objects.filter(parent__isnull=False).order_by('ordering'))

    valid_to = forms.DateField(widget=SelectDateWidget)

class GroupedModelChoiceField(forms.ModelChoiceField):
    def optgroup_from_instance(self, obj):
        return ""

    def __choice_from_instance__(self, obj):
        return obj.id, self.label_from_instance(obj)

    def _get_choices(self):
        if not self.queryset:
            return []

        all_choices = []
        if self.empty_label:
            current_optgroup = ""
            current_optgroup_choices = [("", self.empty_label)]
        else:
            current_optgroup = self.optgroup_from_instance(self.queryset[0])
            current_optgroup_choices = []

        for item in self.queryset:
            optgroup_from_instance = self.optgroup_from_instance(item)
            if current_optgroup != optgroup_from_instance:
                all_choices.append((current_optgroup, current_optgroup_choices))
                current_optgroup_choices = []
                current_optgroup = optgroup_from_instance
            current_optgroup_choices.append(self.__choice_from_instance__(item))

        all_choices.append((current_optgroup, current_optgroup_choices))

        return all_choices

    choices = property(_get_choices, forms.ChoiceField._set_choices)


class CategoryChoiceField(GroupedModelChoiceField):
    def optgroup_from_instance(self, obj):
        return obj.parent.title

为什么以及如何解决它?

PS Django 1.9,python 2.7,OS X.



1> gpichot..:

看看堆栈跟踪.

在预热过程中,Django会导入所有模型和网址.

您应该将queryset初始化移动到OrderForm 的init方法.

更一般的说明,并回答洛伦佐.在所有情况下,您都希望将字段querysets initialisation移动到表单的init方法或将它们移动到您的视图中.为什么?实际上,当Django启动时,它可以导入一些表单,构建表单类,同样的字段类属性也会发生.其结果是,在查询集是获取直接,一劳永逸,输入您的形式和时保持不变,只要你不重装的服务器,所以如果你将数据添加到您的OrderCategory它永远不会出现在你的选择部件.

"解决方法"是将查询集初始化移动到表单的init方法.

在你的情况下:

class OrderForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(OrderForm, self).__init__(*args, **kwargs)
        self.fields['city'].queryset = City.objects.filter(country__code='RU').order_by('name')
        self.fields['category'].queryset = OrderCategory.objects.filter(parent__isnull=False).order_by('ordering')
    class Meta:
       #...
    # ... fields definition

请参阅处理相关Django文档关系的字段.


查询集是惰性的,可以直接在`ModelChoiceField`中使用它们,它足够聪明,可以为每个表单实例单独评估查询集.这里的问题是自定义`_get_choices()`方法在实例化字段时评估查询集,这在首次导入表单时发生.这就是为什么在这种情况下你需要把它移到`__init__`.
推荐阅读
mobiledu2402851203
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有