【问题标题】:Django - Why am I getting an OperationalError (only) when I am using the shell?Django - 为什么我在使用 shell 时会收到 OperationalError(仅)?
【发布时间】:2018-12-25 13:14:22
【问题描述】:

我遇到了一个奇怪的情况。怎么了?

当我从项目目录运行python manage.py shell,导入一个模型(任何模型),并尝试访问它的Model.objectsobjects.all()objects.create(),...),它会抛出一个OperationalError如下引用。

>>> from Interface.models import ClientUser
>>> ClientUser.objects.all()

django.db.utils.OperationalError:没有这样的表:Interface_clientuser

>>> ClientUser.objects.create()

django.db.utils.OperationalError:没有这样的表:Interface_clientuser

我试过删除数据库然后运行python manage.py migrate,关闭所有东西并重新启动我的电脑,然后非常努力地盯着代码(大声笑),但无济于事..

有趣的是,我的单元测试都通过了;包括,例如,调用ClientUser.objects.create()

这是 ClientUser 模型,虽然我不认为模型是问题(所有模型都会发生错误并且单元测试通过..)

class ClientUser(models.Model):
    guid = models.UUIDField(null=True, unique=True)
    username = models.CharField(max_length=256, null=True, unique=True)
    first_name = models.CharField(max_length=256, null=True)
    last_name = models.CharField(max_length=256, null=True)
    email = models.CharField(max_length=256, null=True)

    def most_recent_device(self):
        return self.devices.order_by('-pk').first()

    # I just put this classmethod in. I'm not sure if this will work, and went to the shell to try it, and that's when I noticed this issue. I've tried commenting it out and it makes no difference.    
    @classmethod
    def get_by_guid(cls, guid):
        return cls.objects.get(guid=guid)

这是来自 shell 的完整堆栈跟踪(上图):

>>> from Interface.models import ClientUser
>>> ClientUser.objects.all()
Traceback (most recent call last):
  File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Program Files\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: Interface_clientuser

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

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Program Files\Python37\lib\site-packages\django\db\models\query.py", line 248, in __repr__
    data = list(self[:REPR_OUTPUT_SIZE + 1])
  File "C:\Program Files\Python37\lib\site-packages\django\db\models\query.py", line 272, in __iter__
    self._fetch_all()
  File "C:\Program Files\Python37\lib\site-packages\django\db\models\query.py", line 1179, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "C:\Program Files\Python37\lib\site-packages\django\db\models\query.py", line 53, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "C:\Program Files\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1068, in execute_sql
    cursor.execute(sql, params)
  File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 100, in execute
    return super().execute(sql, params)
  File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Program Files\Python37\lib\site-packages\django\db\utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Program Files\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: Interface_clientuser

【问题讨论】:

    标签: python django python-3.x


    【解决方案1】:

    您的表尚未创建...

    运行 makemigrations 以检查是否存在要应用的迁移

    python manage.py makemigrations
    

    然后运行 ​​migrate 将所有迁移应用到数据库中

    python manage.py migrate
    

    编辑您使用了多少个数据库?这个错误也是 sqlite 引发的,您是否在设置和测试中使用了 sqlite?

    【讨论】:

    • 这也是我的第一个想法。不幸的是,我已经尝试过运行python manage.py makemigrationspython manage.py migrate。甚至删除数据库并运行迁移命令(请参阅有问题的详细信息)
    • 1 个数据库,sqllite。同样重要的是要注意单元测试有效
    • 是的,我开始认为您的 teste 案例可能忽略了错误或可能使用其他数据库
    • 仔细检查您的“manage.py”文件是否调用了正确的“设置”,如果您使用多个设置文件,您的管理人员可能正在使用生产数据库或类似的东西调用一个不同的设置跨度>
    • 是的,你可以运行 runserver,或者在你的 manage.py 中更改它(在你的 wsgi 中你使用 WSGI 服务器),通常我使用环境变量来定义哪个环境是... dev , qa, prod 并根据它调用我的设置
    【解决方案2】:

    除此之外还需要额外的魔法:

    python manage.py makemigrations
    python manage.py migrate
    

    运行这个奥术野兽:

    python manage.py migrate --run-syncdb
    

    欢欣鼓舞!:

    C:\Code\Py\django\HealthCheck>python manage.py migrate --run-syncdb
    Operations to perform:
      Synchronize unmigrated apps: Interface, messages, rest_framework, staticfiles
      Apply all migrations: admin, auth, contenttypes, sessions
    Synchronizing apps without migrations:
      Creating tables...
        Creating table Interface_clientuser
        Creating table Interface_clientgroup
        Creating table Interface_device
        Creating table Interface_supportrequest
        Creating table Interface_fcmmessage
        Creating table Interface_healthcheckalert
        Running deferred SQL...
    Running migrations:
      No migrations to apply.
    
    C:\Code\Py\django\HealthCheck>python manage.py shell
    Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    (InteractiveConsole)
    >>> from Interface.models import ClientUser
    >>> ClientUser.objects.all()
    <QuerySet []>
    

    【讨论】:

    • 你的 Django 版本是多少? --run-syncdb 我很确定适用于旧版本(如果我没记错的话,1.7 或更低)
    • @DiegoVinícius 2.0.7
    • @DiegoVinícius 我不知道为什么突然有必要这样做......app_name = "Interface" in Interface.urls.py,但它一直是......疯狂......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 2022-09-27
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多