gpt4 book ai didi

Django 操作错误 : missing table; migration does not recognize missing table

转载 作者:太空狗 更新时间:2023-10-30 01:57:09 26 4
gpt4 key购买 nike

我在 Django 1.7 中遇到问题,我正在尝试将用户保存到表中,但我收到一个错误,指出该表不存在。

这是我正在执行的代码:

from django.conf import settings
from django.contrib.auth import BACKEND_SESSION_KEY, SESSION_KEY, get_user_model
User = get_user_model()
from django.contrib.sessions.backends.db import SessionStore
from django.core.management.base import BaseCommand
class Command(BaseCommand):

def handle(self, email, *_, **__):

session_key = create_pre_authenticated_session(email)
self.stdout.write(session_key)


def create_pre_authenticated_session(email):
user = User.objects.create(email=email)
session = SessionStore()
session[SESSION_KEY] = user.pk
session[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0]
session.save()
return session.session_key

然而,在

    user = User.objects.create(email=email)  

我收到一条错误消息:

 django.db.utils.OperationalError: no such table: accounts_user  

这是我试图用来构建表的 accounts/models.py 中的用户模型:

from django.db import models
from django.utils import timezone

class User(models.Model):
email = models.EmailField(primary_key=True)
last_login = models.DateTimeField(default=timezone.now)
REQUIRED_FIELDS = ()
USERNAME_FIELD = 'email'

def is_authenticated(self):
return True

我已经使用 'manage.py accounts 0001.initial' 针对此迁移运行了 sqlmigrate,并且我已经返回了正确的创建表 SQL,但是正在运行 'manage.py migrate' 给我以下内容:

Operations to perform:
Apply all migrations: sessions, admin, lists, contenttypes, accounts, auth
Running migrations:
No migrations to apply.

迁移只是从 shell 运行“makemigration”的结果,没有自定义代码。我确实看到包含的应用程序中列出了帐户,但没有运行迁移,所以我的网站处于一个奇怪的位置,当我尝试使用它时 Django 说该表丢失,但 Django 说它存在当我尝试运行迁移以创建它。
为什么 Django 错误地认为该表已经存在,而我可以查看数据库并发现它不存在?

最佳答案

@user856358 您对其他 sqlite 文件的评论似乎是根本原因。我遇到了同样的错误,通过删除该文件并运行另一个迁移解决了这个问题。在我的例子中,文件位于 settings.py 中指定的位置:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, '../database/db.sqlite3'),
}
}

通过删除那里的 .sqlite3 文件,我能够成功运行迁移并解决 no-such-table 错误...

django.db.utils.OperationalError: no such table: accounts_user
$ rm ../database/db.sqlite3
$ python3 manage.py migrate

关于Django 操作错误 : missing table; migration does not recognize missing table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27814144/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com