Python Django - 没有这样的表异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34548768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:08:59  来源:igfitidea点击:

Django - no such table exception

pythondjangosqlitemigratemakemigrations

提问by Milano

In Django, I've added some models into models.py. After manage.py makemigrations, manage.py migrateraised this exception:

在 Django 中,我将一些模型添加到models.py. 之后manage.py makemigrationsmanage.py migrate引发了这个异常:

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

So I've removed all old migrations and run makemigrationsand migrateagain which seemed to work.

所以我已经删除了所有旧的迁移makemigrationsmigrate再次运行,这似乎有效。

Unfortunately, I've noticed that it didn't helped because when I try to click on User customer profilesof User translator profilesit raises exception:

不幸的是,我注意到,它并没有帮助,因为当我尝试点击User customer profilesUser translator profiles它会引发异常:

Environment:

环境:

Request Method: GET
Request URL: http://127.0.0.1:8000/admin/auth_test/usertranslatorprofile/

Django Version: 1.8.7
Python Version: 2.7.10
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'auth_test')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickHymaning.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')


Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in wrapper
  618.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
  57.         response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in inner
  233.             return view(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapper
  34.             return bound_func(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in bound_func
  30.                 return func.__get__(self, type(self))(*args2, **kwargs2)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in changelist_view
  1550.                 self.list_max_show_all, self.list_editable, self)
File "C:\Python27\lib\site-packages\django\contrib\admin\views\main.py" in __init__
  82.         self.get_results(request)
File "C:\Python27\lib\site-packages\django\contrib\admin\views\main.py" in get_results
  177.         result_count = paginator.count
File "C:\Python27\lib\site-packages\django\core\paginator.py" in _get_count
  72.                 self._count = self.object_list.count()
File "C:\Python27\lib\site-packages\django\db\models\query.py" in count
  318.         return self.query.get_count(using=self.db)
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in get_count
  466.         number = obj.get_aggregation(using, ['__count'])['__count']
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in get_aggregation
  447.         result = compiler.execute_sql(SINGLE)
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  840.             cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py" in execute
  79.             return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py" in execute
  64.                 return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\utils.py" in __exit__
  98.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py" in execute
  64.                 return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
  318.         return Database.Cursor.execute(self, query, params)

Exception Type: OperationalError at /admin/auth_test/usertranslatorprofile/
Exception Value: no such table: auth_test_usertranslatorprofile

I'm attaching my files:

我附上我的文件:

MODELS.PY:

模型.PY:

from django.db import models
from django.contrib.auth.models import User

class Language(models.Model):
    shortcut = models.CharField(max_length=6)
    name = models.CharField(max_length=50)
    price_per_sign = models.FloatField()

class UserTranslatorProfile(models.Model):
    user = models.OneToOneField(User)
    languages = models.ManyToManyField(Language)
    price_per_word = models.FloatField()

class UserCustomerProfile(models.Model):
    user = models.OneToOneField(User)

ADMIN.PY:

管理员.PY:

from django import forms
from .models import Language
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class FreelancerRegistrationForm(forms.Form):
    language = forms.ModelChoiceField(queryset=Language.objects.all().order_by('shortcut'))

Do you know where is the problem? Thanks

你知道问题出在哪里吗?谢谢

采纳答案by aks

I solved the same problem with these steps :

我用这些步骤解决了同样的问题:

  • Delete your database (db.sqlite3in my case) in your project directory
  • Remove everything from __pycache__folder under your project subdirectory
  • For the application you are trying to fix, go to the folder and clear migrationsand __pycache__directories
  • 删除db.sqlite3项目目录中的数据库(在我的情况下)
  • __pycache__项目子目录下的文件夹中删除所有内容
  • 您正在试图修复应用程序,进入该文件夹并清除migrations__pycache__目录

When you are sure you have cleared all the above files, run:

当您确定已清除所有上述文件时,请运行:

python manage.py makemigrations
python manage.py migrate

I hope this helps.

我希望这有帮助。

回答by Terry Brown

Another case wihch can generate the no such tableerror. If your views.py or similar executes code that tries to access the DB when imported, i.e. importing views.py has side effects, then starting from scratch won't work.

另一种情况会产生无此类表错误。如果您的 views.py 或类似文件在导入时执行试图访问数据库的代码,即导入 views.py 有副作用,那么从头开始将不起作用

This happens when your code was working with an existing DB, and now you're trying to start without a DB. Just change views.py so it can be imported without side effects. If you don't want to fix the design, do something like:

当您的代码使用现有数据库时会发生这种情况,而现在您试图在没有数据库的情况下开始。只需更改 views.py 即可导入而不会产生副作用。如果您不想修复设计,请执行以下操作:

from django.db.utils import OperationalError
format_list = [('', '(all)')]
geom_type_list = [('', '(all)')]
try:
    format_list.extend([(i[0],i[0]) 
        for i in Format.objects.values_list('name')])
    geom_type_list.extend([(i[0],i[0]) 
        for i in Geom_type.objects.values_list('name')])
except OperationalError:
    pass  # happens when db doesn't exist yet, views.py should be
          # importable without this side effect

回答by kotrfa

Adding to terry_brown's answer, this is what cause my problems. I had a custom user model with ForeignKey to another model. And I set defaults to first object in the DB. It worked when I had the data in the database. But when I started from scratch, it didn't work because it was executed immediately when imported (so not even migration went through).

添加到 terry_brown 的答案中,这就是导致我遇到问题的原因。我有一个带有外键的自定义用户模型到另一个模型。我将默认值设置为数据库中的第一个对象。当我在数据库中有数据时,它就起作用了。但是当我从头开始时,它不起作用,因为它在导入时立即执行(因此甚至没有通过迁移)。

class User(AbstractBaseUser, PermissionsMixin):
    subscription_plan = models.ForeignKey(SubscriptionPlan, default=SubscriptionPlan.objects.first().id)

I had to sacrifice that default(commenting it out).

我不得不牺牲它default(注释掉它)。

UPDATE: A better solution would be to prepopulate your database with initial migration or fixtures.

更新:更好的解决方案是使用初始迁移或夹具预先填充您的数据库。

回答by Petr

Maybe out of time but...I have same problem when I tried to "clone" Django 1.11 installation into other directory and then with initial try to manage makemigrations.

也许过时了,但是......当我尝试将 Django 1.11 安装“克隆”到其他目录,然后最初尝试管理 makemigrations 时,我遇到了同样的问题。

I solve the problem following way:

我通过以下方式解决问题:

  1. settup initial Django installation and creating main application by:
  1. 设置初始 Django 安装并通过以下方式创建主应用程序:

django-admin.py startproject app_name

django-admin.py startproject app_name

  1. initial migrations manage makemigrations, manage migrate

  2. Setup the superuser:

  1. 初始迁移管理 makemigrations,管理迁移

  2. 设置超级用户:

manage createsuperuser

管理创建超级用户

  1. copy all files and directories (Django applications) except the urls.py and settings.py in main directory

  2. Added all apps into INSTALLED_APPS

  3. manage makemigrations, manage migrate

  4. Copied settings.py and urls.py from source Django application directory

  1. 复制除主目录中的 urls.py 和 settings.py 之外的所有文件和目录(Django 应用程序)

  2. 将所有应用添加到 INSTALLED_APPS

  3. 管理 makemigrations,管理迁移

  4. 从源 Django 应用程序目录复制 settings.py 和 urls.py

Thats it no errors and all is working fine.

那就是没有错误,一切正常。

Petr

彼得

回答by Batman

If someone else has this problem and the accepted solution is not working, have a look at your db path, the db path should be absolute path, 'NAME': '/pathto-db/default.db',

如果其他人有这个问题并且接受的解决方案不起作用,请查看您的数据库路径,数据库路径应该是绝对路径, 'NAME': '/pathto-db/default.db',

Link

关联

回答by Ajmal Aamir

run below command. It solves me once this issue

在命令下运行。一旦这个问题它就解决了我

manage.py migrate --run-syncdb

manage.py migrate --run-syncdb

回答by adam

To solve it I did this (on Ubuntu, you'll need to adapt the commands for Windows):

为了解决这个问题,我做了这个(在 Ubuntu 上,你需要调整 Windows 的命令):

1. Remove all the migration files

1. 删除所有迁移文件

find . -path "*/migrations/*.py" -not -name "__init__.py" -delete

find . -path "*/migrations/*.pyc"  -delete

2. Delete db.sqlite3

2.删除db.sqlite3

rm db.sqlite3

3. Create and run the migrations:

3. 创建并运行迁移:

python manage.py makemigrations
python manage.py migrate

4. Sync the database:

4. 同步数据库:

manage.py migrate --run-syncdb

Bit of a pain as you need to delete your database, but fine for a test system. Got all but the final step from this generally excellent resource: https://simpleisbetterthancomplex.com/tutorial/2016/07/26/how-to-reset-migrations.html

删除数据库有点麻烦,但对于测试系统来说很好。从这个普遍优秀的资源中获得了最后一步:https: //simpleisbetterthancomplex.com/tutorial/2016/07/26/how-to-reset-migrations.html

回答by Mansoorulhaq Mansoor

While running any management command "django.contrib.admin" automatically attempts to discover and admin.py modules in installed apps.

在运行任何管理命令时“django.contrib.admin”会自动尝试在已安装的应用程序中发现和 admin.py 模块。

If there is a code related to database, it runs automatically and tries to load data from database when it can not find data related table in database throw this Error.

如果有与数据库相关的代码,它会自动运行并尝试从数据库中加载数据,当它在数据库中找不到数据相关表时抛出此错误。

To fix this error just change "django.contrib.admin"in INSTALLED_APPSto "django.contrib.admin.apps.SimpleAdminConfig", it will prevent "django.contrib.admin" from auto discovering and running admin modules.

为了解决这个错误,只是变化"django.contrib.admin"INSTALLED_APPS"django.contrib.admin.apps.SimpleAdminConfig",这将防止“django.contrib.admin”从自动发现和管理运行模块。

django.contrib.admin automatically performs auto discovery of admin modules in installed applications. To prevent it, change your INSTALLED_APPS to contain 'django.contrib.admin.apps.SimpleAdminConfig' instead of 'django.contrib.admin'.

https://docs.djangoproject.com/en/3.0/ref/applications/#troubleshooting

django.contrib.admin 在已安装的应用程序中自动执行管理模块的自动发现。为了防止它,将你的 INSTALLED_APPS 更改为包含 'django.contrib.admin.apps.SimpleAdminConfig' 而不是 'django.contrib.admin'。

https://docs.djangoproject.com/en/3.0/ref/applications/#troubleshooting

回答by Mohsin Mahmood

If none of the above solution worked for you then add the appnamealong with the makemigrationand migratecommand.

如果上述解决方案都不适合您appname,则将makemigrationmigrate命令一起添加。

 makemigration login
 migrate login

That might help you to figure out the problem.

这可能会帮助您找出问题所在。

回答by Ashish Gupta

Follow this steps to get fixed this issue.

请按照以下步骤解决此问题。

python manage.py migrate --fake APPNAME zero

This will make your migration to fake. Now you can run the migrate script

这将使您的迁移成为假的。现在您可以运行迁移脚本

python manage.py migrate APPNAME

OR

或者

python manage.py migrate

Tables will be created and you solved your problem.. Cheers!!!

将创建表格,您解决了您的问题..干杯!!!