django.db.utils.ProgrammingError: relation "bot_trade" does not exist
django.db.utils.ProgrammingError: relation "bot_trade" does not exist
我正在尝试在 cookeicutter 上建立一个网站,我创建了一个名为 "bots" 的新应用程序并在模型中添加了一个名为 Trade 的 class,它列出了 2 个参数,"titles" 和"units"。迁移并 运行 连接服务器后,当我打开管理面板并单击面板内的“+ 添加”按钮以创建交易时(见图)。 Django 网页 returns 这个错误:
django.db.utils.ProgrammingError: relation "bot_trade" does not exist
LINE 1: ...."id", "bots_unit"."sell", "bots_unit"."buy" FROM "bots_unit...
附加信息:
运行 我的 django 在 docker 和 postgreSQL
pic of admin panel
Models.py
from django.db import models
from datetime import date
#from django.contrib.auth.models import AbstractUser
#from .models import User
from django.urls import reverse
from django.urls import reverse_lazy
from django.conf import settings
import uuid
class Unit(models.Model):
TRADE_UNIT = (
('ETH', 'Ethereum'),
('BTC', 'Bitcoin'),
('LTC', 'Litecoin'),
('IOT', 'IOTA'),
('OMG', 'OmiseGo'),
('BCH', 'BitcoinCash'),
)
sell = models.CharField(max_length=3, choices=TRADE_UNIT, blank=True, default='ETH', help_text='Currency to Sell')
buy = models.CharField(max_length=3, choices=TRADE_UNIT, blank=True, default='BTC', help_text='Currency to Buy')
def get_absolute_url(self):
"""
Returns the url to access a particular author instance.
"""
return reverse('unit-detail', args=[str(self.id)])
def __str__(self):
"""
String for representing the Model object.
"""
return '%s, %s' % (self.sell, self.buy)
class Meta:
db_table = 'bots_unit'
ordering = ['sell','buy']
class Trade(models.Model):
title = models.CharField(max_length=200)
unit = models.ForeignKey('Unit', on_delete=models.SET_NULL, null=True)
def __str__(self):
"""
String for representing the Model object.
"""
return self.title
def get_absolute_url(self):
"""
Returns the url to access a particular book instance.
"""
return reverse('trade-detail', args=[str(self.id)])
class Meta:
db_table = 'bots_trade'
class TradeInstance(models.Model):
"""
Model representing a specific copy of a book (i.e. that can be borrowed from the library).
"""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular trade across whole database")
trade = models.ForeignKey('Trade', on_delete=models.SET_NULL, null=True)
amount = models.CharField(max_length=200)
price = models.CharField(max_length=200)
imprint = models.CharField(max_length=200)
time_initiated = models.DateTimeField(null=True, blank=True)
#initiator = models.ForeignKey(AbstractUser,
on_delete=models.SET_NULL, null=True, blank=True)
position_status = (
('L', 'Long'),
('S', 'Short'),
)
position = models.CharField(max_length=1, choices=position_status, blank=True, default='L', help_text='Order Type')
class Meta:
ordering = ["position"]
def __str__(self):
"""
String for representing the Model object
"""
return '%s (%s)' % (self.id,self.trade.title)
Admin.py
from django.contrib import admin
from .models import Trade, TradeInstance, Unit
# Define the admin class
@admin.register(Trade)
class TradeAdmin(admin.ModelAdmin):
pass
@admin.register(Unit)
class UnitAdmin(admin.ModelAdmin):
pass
更新1:
我删除了 migrations 文件夹中的内容几次,但这是 运行ning 'makemigrations' 和 'migrate':[=18= 之后 '0001.initial.py' 中当前的内容]
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2017-10-12 17:55
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Trade',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
],
),
migrations.CreateModel(
name='TradeInstance',
fields=[
('id', models.UUIDField(default=uuid.uuid4, help_text='Unique ID for this particular trade across whole database', primary_key=True, serialize=False)),
('amount', models.CharField(max_length=200)),
('price', models.CharField(max_length=200)),
('imprint', models.CharField(max_length=200)),
('time_initiated', models.DateTimeField(blank=True, null=True)),
('position', models.CharField(blank=True, choices=[('L', 'Long'), ('S', 'Short')], default='L', help_text='Order Type', max_length=1)),
('trade', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='bots.Trade')),
],
options={
'ordering': ['position'],
},
),
migrations.CreateModel(
name='Unit',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('sell', models.CharField(blank=True, choices=[('ETH', 'Ethereum'), ('BTC', 'Bitcoin'), ('LTC', 'Litecoin'), ('IOT', 'IOTA'), ('OMG', 'OmiseGo'), ('BCH', 'BitcoinCash')], default='ETH', help_text='Currency to Sell', max_length=3)),
('buy', models.CharField(blank=True, choices=[('ETH', 'Ethereum'), ('BTC', 'Bitcoin'), ('LTC', 'Litecoin'), ('IOT', 'IOTA'), ('OMG', 'OmiseGo'), ('BCH', 'BitcoinCash')], default='BTC', help_text='Currency to Buy', max_length=3)),
],
options={
'ordering': ['sell', 'buy'],
},
),
migrations.AddField(
model_name='trade',
name='unit',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='bots.Unit'),
),
]
当我运行'showmigrations':
dominic@dom-Inspiron-7559:~/Desktop/Projects/vickibot/vicki$ docker-compose -focal.yml run django python manage.py showmigrations
Postgres is up - continuing...
account
[X] 0001_initial
[X] 0002_email_max_length
admin
[X] 0001_initial
[X] 0002_logentry_remove_auto_add
auth
[X] 0001_initial
[X] 0002_alter_permission_name_max_length
[X] 0003_alter_user_email_max_length
[X] 0004_alter_user_username_opts
[X] 0005_alter_user_last_login_null
[X] 0006_require_contenttypes_0002
[X] 0007_alter_validators_add_error_messages
[X] 0008_alter_user_username_max_length
bots
[X] 0001_initial
contenttypes
[X] 0001_initial
[X] 0002_remove_content_type_name
sessions
[X] 0001_initial
sites
[X] 0001_initial
[X] 0002_alter_domain_unique
[X] 0003_set_site_domain_and_name
socialaccount
[X] 0001_initial
[X] 0002_token_max_lengths
[X] 0003_extra_data_default_dict
users
[X] 0001_initial
更新2:
'manage.py migrate --fake bots zero' 输出:
dominic@dom-Inspiron-7559:~/Desktop/Projects/vickibot/vicki$ **docker-compose -f local.yml run django python manage.py migrate --fake bots zero**
Postgres is up - continuing...
Operations to perform:
Unapply all migrations: bots
Running migrations:
Rendering model states... DONE
Unapplying bots.0001_initial... FAKED
'manage.py migrate bots' 输出:
dominic@dom-Inspiron-7559:~/Desktop/Projects/vickibot/vicki$ docker-compose -f local.yml run django python manage.py migrate bots
Postgres is up - continuing...
Operations to perform:
Apply all migrations: bots
Running migrations:
Applying bots.0001_initial... OK
您可能还没有为您的机器人应用程序创建任何迁移。您需要指定应用名称才能创建初始迁移:
./manage.py makemigrations bot
然后运行迁移到运行迁移并创建缺失的table:
./manage migrate
当您 运行 showmigrations
时,您可以看到 Django 认为它已经为您的 bots
应用应用了初始迁移。这可能是因为您 运行 --fake
该应用。
bots
[X] 0001_initial
您可以告诉 Django 将迁移标记为未应用,然后重新运行 迁移:
manage.py migrate --fake bots zero
manage.py migrate bots
只要 bots
应用中的 table 尚未创建,这应该可行。如果只创建了一些 table,那么修复数据库会更加棘手。
我遇到了问题,我真的很难找出问题所在。我用 Django 框架制作了一个应用程序。在我的本地机器上一切正常,包括数据库。只是,当我把我的应用程序放在服务器上时,我想迁移数据库,但是我有这个错误:
Traceback (most recent call last):
File "/home/thomas/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedTable: relation "administration_parks" does not exist
LINE 1: ...name", "administration_parks"."availability" FROM "administr...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
utility.execute()
File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute
output = self.handle(*args, **options)
File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 75, in handle
self.check(databases=[database])
File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/base.py", line 419, in check
all_issues = checks.run_checks(
File "/home/thomas/env/lib/python3.8/site-packages/django/core/checks/registry.py", line 76, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "/home/thomas/env/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/thomas/env/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File "/home/thomas/env/lib/python3.8/site-packages/django/urls/resolvers.py", line 412, in check
for pattern in self.url_patterns:
File "/home/thomas/env/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/thomas/env/lib/python3.8/site-packages/django/urls/resolvers.py", line 598, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/thomas/env/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/thomas/env/lib/python3.8/site-packages/django/urls/resolvers.py", line 591, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 848, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/thomas/AnimauBoue/AnimauBoue/urls.py", line 21, in <module>
url(r'^', include('administration.urls')),
File "/home/thomas/env/lib/python3.8/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 848, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/thomas/AnimauBoue/administration/urls.py", line 4, in <module>
from .views import index
File "/home/thomas/AnimauBoue/administration/views.py", line 12, in <module>
from .forms import ConnectionForm, UpdateDataForm, AddClientForm, SelectParkAndClientForm, DogForm, AddDog
File "/home/thomas/AnimauBoue/administration/forms.py", line 26, in <module>
class SelectParkAndClientForm(forms.Form):
File "/home/thomas/AnimauBoue/administration/forms.py", line 31, in SelectParkAndClientForm
for park in parks:
File "/home/thomas/env/lib/python3.8/site-packages/django/db/models/query.py", line 280, in __iter__
self._fetch_all()
File "/home/thomas/env/lib/python3.8/site-packages/django/db/models/query.py", line 1324, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/home/thomas/env/lib/python3.8/site-packages/django/db/models/query.py", line 51, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/home/thomas/env/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql
cursor.execute(sql, params)
File "/home/thomas/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute
return super().execute(sql, params)
File "/home/thomas/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/thomas/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/thomas/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/thomas/env/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/thomas/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "administration_parks" does not exist
LINE 1: ...name", "administration_parks"."availability" FROM "administr...
事实上,我开始了解到 Django 在迁移数据库时似乎对 urls.py 应用程序的视图执行了一些操作。就我而言,这就是问题所在。所以解决方案是:
评论我所有的 url 模式,然后进行迁移,成功了!
在这个阶段,它允许我创建模型中的表格。但是 Django 的默认表没有创建,因为我不再有任何 url 模式。所以我 取消注释 urls.py 中的所有 url,在我的服务器上重新拉取,然后重做迁移 。至此,django默认创建的所有表都创建好了。
您可能会遇到相同问题的另一个原因是,您尝试访问数据的时间早于在数据库中创建数据的时间。例如,由于这行代码,我无法执行迁移:
cat_choices = [(cat, cat) for cat in Category.objects.all().values_list('title', flat=True)]
问题是:
Category.objects.all().values_list()
问题是代码试图在类别的数据库 table 存在之前从模型类别中获取值。因此,它无法执行 makemigrations 和 migrate。要解决此问题,您可以将代码包含在 try except 块中,并将 ProgrammingError 和 OperationalError 作为异常。
try:
cat_choices = Category.objects.all().values_list('title')
except (OperationalError, ProgrammingError) as e:
cat_choices=[]
我正在尝试在 cookeicutter 上建立一个网站,我创建了一个名为 "bots" 的新应用程序并在模型中添加了一个名为 Trade 的 class,它列出了 2 个参数,"titles" 和"units"。迁移并 运行 连接服务器后,当我打开管理面板并单击面板内的“+ 添加”按钮以创建交易时(见图)。 Django 网页 returns 这个错误:
django.db.utils.ProgrammingError: relation "bot_trade" does not exist
LINE 1: ...."id", "bots_unit"."sell", "bots_unit"."buy" FROM "bots_unit...
附加信息: 运行 我的 django 在 docker 和 postgreSQL
pic of admin panel
Models.py
from django.db import models
from datetime import date
#from django.contrib.auth.models import AbstractUser
#from .models import User
from django.urls import reverse
from django.urls import reverse_lazy
from django.conf import settings
import uuid
class Unit(models.Model):
TRADE_UNIT = (
('ETH', 'Ethereum'),
('BTC', 'Bitcoin'),
('LTC', 'Litecoin'),
('IOT', 'IOTA'),
('OMG', 'OmiseGo'),
('BCH', 'BitcoinCash'),
)
sell = models.CharField(max_length=3, choices=TRADE_UNIT, blank=True, default='ETH', help_text='Currency to Sell')
buy = models.CharField(max_length=3, choices=TRADE_UNIT, blank=True, default='BTC', help_text='Currency to Buy')
def get_absolute_url(self):
"""
Returns the url to access a particular author instance.
"""
return reverse('unit-detail', args=[str(self.id)])
def __str__(self):
"""
String for representing the Model object.
"""
return '%s, %s' % (self.sell, self.buy)
class Meta:
db_table = 'bots_unit'
ordering = ['sell','buy']
class Trade(models.Model):
title = models.CharField(max_length=200)
unit = models.ForeignKey('Unit', on_delete=models.SET_NULL, null=True)
def __str__(self):
"""
String for representing the Model object.
"""
return self.title
def get_absolute_url(self):
"""
Returns the url to access a particular book instance.
"""
return reverse('trade-detail', args=[str(self.id)])
class Meta:
db_table = 'bots_trade'
class TradeInstance(models.Model):
"""
Model representing a specific copy of a book (i.e. that can be borrowed from the library).
"""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular trade across whole database")
trade = models.ForeignKey('Trade', on_delete=models.SET_NULL, null=True)
amount = models.CharField(max_length=200)
price = models.CharField(max_length=200)
imprint = models.CharField(max_length=200)
time_initiated = models.DateTimeField(null=True, blank=True)
#initiator = models.ForeignKey(AbstractUser,
on_delete=models.SET_NULL, null=True, blank=True)
position_status = (
('L', 'Long'),
('S', 'Short'),
)
position = models.CharField(max_length=1, choices=position_status, blank=True, default='L', help_text='Order Type')
class Meta:
ordering = ["position"]
def __str__(self):
"""
String for representing the Model object
"""
return '%s (%s)' % (self.id,self.trade.title)
Admin.py
from django.contrib import admin
from .models import Trade, TradeInstance, Unit
# Define the admin class
@admin.register(Trade)
class TradeAdmin(admin.ModelAdmin):
pass
@admin.register(Unit)
class UnitAdmin(admin.ModelAdmin):
pass
更新1: 我删除了 migrations 文件夹中的内容几次,但这是 运行ning 'makemigrations' 和 'migrate':[=18= 之后 '0001.initial.py' 中当前的内容]
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2017-10-12 17:55
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Trade',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
],
),
migrations.CreateModel(
name='TradeInstance',
fields=[
('id', models.UUIDField(default=uuid.uuid4, help_text='Unique ID for this particular trade across whole database', primary_key=True, serialize=False)),
('amount', models.CharField(max_length=200)),
('price', models.CharField(max_length=200)),
('imprint', models.CharField(max_length=200)),
('time_initiated', models.DateTimeField(blank=True, null=True)),
('position', models.CharField(blank=True, choices=[('L', 'Long'), ('S', 'Short')], default='L', help_text='Order Type', max_length=1)),
('trade', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='bots.Trade')),
],
options={
'ordering': ['position'],
},
),
migrations.CreateModel(
name='Unit',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('sell', models.CharField(blank=True, choices=[('ETH', 'Ethereum'), ('BTC', 'Bitcoin'), ('LTC', 'Litecoin'), ('IOT', 'IOTA'), ('OMG', 'OmiseGo'), ('BCH', 'BitcoinCash')], default='ETH', help_text='Currency to Sell', max_length=3)),
('buy', models.CharField(blank=True, choices=[('ETH', 'Ethereum'), ('BTC', 'Bitcoin'), ('LTC', 'Litecoin'), ('IOT', 'IOTA'), ('OMG', 'OmiseGo'), ('BCH', 'BitcoinCash')], default='BTC', help_text='Currency to Buy', max_length=3)),
],
options={
'ordering': ['sell', 'buy'],
},
),
migrations.AddField(
model_name='trade',
name='unit',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='bots.Unit'),
),
]
当我运行'showmigrations':
dominic@dom-Inspiron-7559:~/Desktop/Projects/vickibot/vicki$ docker-compose -focal.yml run django python manage.py showmigrations
Postgres is up - continuing...
account
[X] 0001_initial
[X] 0002_email_max_length
admin
[X] 0001_initial
[X] 0002_logentry_remove_auto_add
auth
[X] 0001_initial
[X] 0002_alter_permission_name_max_length
[X] 0003_alter_user_email_max_length
[X] 0004_alter_user_username_opts
[X] 0005_alter_user_last_login_null
[X] 0006_require_contenttypes_0002
[X] 0007_alter_validators_add_error_messages
[X] 0008_alter_user_username_max_length
bots
[X] 0001_initial
contenttypes
[X] 0001_initial
[X] 0002_remove_content_type_name
sessions
[X] 0001_initial
sites
[X] 0001_initial
[X] 0002_alter_domain_unique
[X] 0003_set_site_domain_and_name
socialaccount
[X] 0001_initial
[X] 0002_token_max_lengths
[X] 0003_extra_data_default_dict
users
[X] 0001_initial
更新2:
'manage.py migrate --fake bots zero' 输出:
dominic@dom-Inspiron-7559:~/Desktop/Projects/vickibot/vicki$ **docker-compose -f local.yml run django python manage.py migrate --fake bots zero**
Postgres is up - continuing...
Operations to perform:
Unapply all migrations: bots
Running migrations:
Rendering model states... DONE
Unapplying bots.0001_initial... FAKED
'manage.py migrate bots' 输出:
dominic@dom-Inspiron-7559:~/Desktop/Projects/vickibot/vicki$ docker-compose -f local.yml run django python manage.py migrate bots
Postgres is up - continuing...
Operations to perform:
Apply all migrations: bots
Running migrations:
Applying bots.0001_initial... OK
您可能还没有为您的机器人应用程序创建任何迁移。您需要指定应用名称才能创建初始迁移:
./manage.py makemigrations bot
然后运行迁移到运行迁移并创建缺失的table:
./manage migrate
当您 运行 showmigrations
时,您可以看到 Django 认为它已经为您的 bots
应用应用了初始迁移。这可能是因为您 运行 --fake
该应用。
bots
[X] 0001_initial
您可以告诉 Django 将迁移标记为未应用,然后重新运行 迁移:
manage.py migrate --fake bots zero
manage.py migrate bots
只要 bots
应用中的 table 尚未创建,这应该可行。如果只创建了一些 table,那么修复数据库会更加棘手。
我遇到了问题,我真的很难找出问题所在。我用 Django 框架制作了一个应用程序。在我的本地机器上一切正常,包括数据库。只是,当我把我的应用程序放在服务器上时,我想迁移数据库,但是我有这个错误:
Traceback (most recent call last):
File "/home/thomas/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedTable: relation "administration_parks" does not exist
LINE 1: ...name", "administration_parks"."availability" FROM "administr...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
utility.execute()
File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute
output = self.handle(*args, **options)
File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 75, in handle
self.check(databases=[database])
File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/base.py", line 419, in check
all_issues = checks.run_checks(
File "/home/thomas/env/lib/python3.8/site-packages/django/core/checks/registry.py", line 76, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "/home/thomas/env/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/thomas/env/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File "/home/thomas/env/lib/python3.8/site-packages/django/urls/resolvers.py", line 412, in check
for pattern in self.url_patterns:
File "/home/thomas/env/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/thomas/env/lib/python3.8/site-packages/django/urls/resolvers.py", line 598, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/thomas/env/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/thomas/env/lib/python3.8/site-packages/django/urls/resolvers.py", line 591, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 848, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/thomas/AnimauBoue/AnimauBoue/urls.py", line 21, in <module>
url(r'^', include('administration.urls')),
File "/home/thomas/env/lib/python3.8/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 848, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/thomas/AnimauBoue/administration/urls.py", line 4, in <module>
from .views import index
File "/home/thomas/AnimauBoue/administration/views.py", line 12, in <module>
from .forms import ConnectionForm, UpdateDataForm, AddClientForm, SelectParkAndClientForm, DogForm, AddDog
File "/home/thomas/AnimauBoue/administration/forms.py", line 26, in <module>
class SelectParkAndClientForm(forms.Form):
File "/home/thomas/AnimauBoue/administration/forms.py", line 31, in SelectParkAndClientForm
for park in parks:
File "/home/thomas/env/lib/python3.8/site-packages/django/db/models/query.py", line 280, in __iter__
self._fetch_all()
File "/home/thomas/env/lib/python3.8/site-packages/django/db/models/query.py", line 1324, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/home/thomas/env/lib/python3.8/site-packages/django/db/models/query.py", line 51, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/home/thomas/env/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql
cursor.execute(sql, params)
File "/home/thomas/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute
return super().execute(sql, params)
File "/home/thomas/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/thomas/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/thomas/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/thomas/env/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/thomas/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "administration_parks" does not exist
LINE 1: ...name", "administration_parks"."availability" FROM "administr...
事实上,我开始了解到 Django 在迁移数据库时似乎对 urls.py 应用程序的视图执行了一些操作。就我而言,这就是问题所在。所以解决方案是:
评论我所有的 url 模式,然后进行迁移,成功了!
在这个阶段,它允许我创建模型中的表格。但是 Django 的默认表没有创建,因为我不再有任何 url 模式。所以我 取消注释 urls.py 中的所有 url,在我的服务器上重新拉取,然后重做迁移 。至此,django默认创建的所有表都创建好了。
您可能会遇到相同问题的另一个原因是,您尝试访问数据的时间早于在数据库中创建数据的时间。例如,由于这行代码,我无法执行迁移:
cat_choices = [(cat, cat) for cat in Category.objects.all().values_list('title', flat=True)]
问题是:
Category.objects.all().values_list()
问题是代码试图在类别的数据库 table 存在之前从模型类别中获取值。因此,它无法执行 makemigrations 和 migrate。要解决此问题,您可以将代码包含在 try except 块中,并将 ProgrammingError 和 OperationalError 作为异常。
try:
cat_choices = Category.objects.all().values_list('title')
except (OperationalError, ProgrammingError) as e:
cat_choices=[]