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

标签 python django

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

Traceback (most recent call last):
  File "/Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py", line 41, in <module>
    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 <module>
    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 <module>
    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 <module>
    from orders.views import CreateOrderView, OrdersView, OrderView
  File "/Users/rankor/src/python/web/Auction/Auction/orders/views.py", line 7, in <module>
    from orders.forms import OrderForm
  File "/Users/rankor/src/python/web/Auction/Auction/orders/forms.py", line 47, in <module>
    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

为什么以及如何解决?

附言Django 1.9、python 2.7、OS X。

最佳答案

查看堆栈跟踪。

在预热过程中,Django 导入所有模型和 url。

您应该将查询集初始化移动到 OrderForm 的 init 方法。

更一般的说明,并回答 Lorenzo。在所有情况中,您希望将字段查询集初始化移动到表单的 init 方法或将它们移动到您的 View 。为什么?实际上,当 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

参见 Fields which handle relationships获取相关的 Django 文档。

关于python - 删除迁移和 makemigrations 后的 django.db.utils.OperationalError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34249298/

相关文章:

python - mtTkinter 不会终止线程

python - 在 Python 中解析 hw_clock 输出

python - 用 fabric 模拟 KeyboardInterrupt

python - Django:按 child 的属性排序对象

python - 为什么Django说没有名为views的模块?

python - 在 python 中运行单元测试\集成测试

django - 我如何对 Django URL 进行单元测试?

静态函数变量的 Pythonic 方式(小范围,单一初始化)?

python - 如何在Python中读取和打印Excel文件中的随机行?

python - 了解 django loaddata 或为 fixutes 转储数据的正确方法