mysql “字段列表”中的未知列“”, Django

z9smfwbn  于 2023-08-02  发布在  Mysql
关注(0)|答案(4)|浏览(99)

我使用Django 1.9和MySQL。我想重命名模型中的字段。让我们来看看Django getting started tutorial中的Choice模型。

class Choice(models.Model):
  question = models.ForeignKey(Question)
  choice_text = models.CharField(max_length = 200)
  votes = models.IntegerField(default=0)

字符串
因此,我想将votes字段重命名为votes_count。我创建了一个空迁移,并添加到以下行的操作中:

migrations.RenameField (
    model_name='choice',
    old_name='votes',
    new_name='votes_count',
),


python manage.py migrate之后,数据库表中的字段被重命名。但当我试图用这个模型

def vote(request, question_id):
  question = get_object_or_404(Question, pk=question_id);
  try:
    selected = question.choice_set.get(pk=request.POST['choice'])
  except (KeyError, Choice.DoesNotExist):
    return render(request, 'polls/detail.html', {
      'question':question,
      'error_message':"You didn't select a choice."
    })
  else:
    selected.votes_count += 1
    selected.save()
    return HttpResponseRedirect(reverse('polls:results', args=(question_id)))


我得到了:
字段列表中的未知列“polls_choice.votes”

Traceback:

    File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
      64.                 return self.cursor.execute(sql, params)

    File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/backends/mysql/base.py" in execute
      112.             return self.cursor.execute(query, args)

    File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/cursors.py" in execute
      226.             self.errorhandler(self, exc, value)

    File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/connections.py" in defaulterrorhandler
      36.         raise errorvalue

    File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/cursors.py" in execute
      217.             res = self._query(query)

    File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/cursors.py" in
_query
      378.         rowcount = self._do_query(q)

    File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/cursors.py" in
_do_query
      341.         db.query(q)

    File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/connections.py" in query
      280.             _mysql.connection.query(self, query)

    The above exception ((1054, "Unknown column 'polls_choice.votes' in 'field list'")) was the direct cause of the following exception:

    File "/home/verdigo/venv/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
      149.                     response = self.process_exception_by_middleware(e, request)

    File "/home/verdigo/venv/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
      147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

    File "./polls/views.py" in vote
      23.     selected = question.choice_set.get(pk=request.POST['choice'])

    File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/models/manager.py" in manager_method
      122.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

    File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/models/query.py" in get
      381.         num = len(clone)

    File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/models/query.py" in __len__
      240.         self._fetch_all()

    File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/models/query.py" in _fetch_all
      1074.             self._result_cache = list(self.iterator())

    File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/models/query.py" in __iter__
      52.         results = compiler.execute_sql()

    File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/models/sql/compiler.py" in execute_sql
      848.             cursor.execute(sql, params)

    File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
      79.             return super(CursorDebugWrapper, self).execute(sql, params)

    File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
      64.                 return self.cursor.execute(sql, params)

    File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/utils.py" in
__exit__
      95.                 six.reraise(dj_exc_type, dj_exc_value, traceback)

    File "/home/verdigo/venv/lib/python3.4/site-packages/django/utils/six.py" in reraise
      685.             raise value.with_traceback(tb)

    File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
      64.                 return self.cursor.execute(sql, params)

    File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/backends/mysql/base.py" in execute
      112.             return self.cursor.execute(query, args)

    File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/cursors.py" in execute
      226.             self.errorhandler(self, exc, value)

    File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/connections.py" in defaulterrorhandler
      36.         raise errorvalue

    File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/cursors.py" in execute
      217.             res = self._query(query)

    File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/cursors.py" in
_query
      378.         rowcount = self._do_query(q)

    File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/cursors.py" in
_do_query
      341.         db.query(q)

    File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/connections.py" in query
      280.             _mysql.connection.query(self, query)

    Exception Type: OperationalError at /polls/1/vote/
    Exception Value: (1054, "Unknown column 'polls_choice.votes' in 'field list'")

a0x5cqrl

a0x5cqrl1#

看起来好像您创建并运行了一个迁移,将模型字段从votes重命名为votes_count,但没有同时更新模型。
当Django试图从数据库中获取模型时,它试图选择votes列,因为你的模型中仍然有一个votes字段,你会得到错误,因为该列在数据库中不存在。
通常不需要创建手动迁移。通常,您会重命名模型字段,运行makemigrations,然后运行migrate。让Django创建迁移的好处是,在运行migrate之后,您可以确信数据库与模型同步。

bn31dyow

bn31dyow2#

原因:当创建一个新的一对多外键,用forkey字段指向模型,然后生成表时,会发生此错误
.
解决方法:直接删除数据库,重新构建即可解决。
1:删除数据库数据库表;
2、删除后重新创建,之前创建的代码,直接运行

kh212irz

kh212irz3#

这个问题一直困扰着我,让我陷入了很多的困境,比如摔table等等。我发现的一个简单的解决方案是,当django问你是否要重命名该模型的一个字段时(运行makemigrations时),回答“N”。然后,它基本上执行的是删除您以前的字段并创建新字段。要小心,因为你可能会失去现有领域的数据,所以这与领域,无论是新的或相对容易'重新填充'他们所需的数据。如果你在makemigrations之后得到一个关于在迁移时不能“删除字段”的错误,你可能需要运行--fake。
更新:我对布尔字段做了上述操作,我的数据被保留了下来。尽管我说了N,但它似乎本质上是一个重命名。

cgh8pdjw

cgh8pdjw4#

在我这边,当我添加一个具有oneToMany关系的新列时,迁移失败了。为了避免删除数据和重新创建模型,请下载适用于您的平台的mysql workbench。运行以下代码以插入缺少的列。

use <database_name>;
show tables;
desc <table_name>;
alter table <table_name> add column (< missing field> varchar(255) )

字符串
添加了缺少的列,错误就消失了

相关问题