我在创建一个简单的Django项目时遇到了问题。我在这个项目中的目标是使用Django Admin提供的工具管理我已经拥有的数据库。
我继续解释我已经做了什么,并没有像预期的那样工作。
这是我的外部模型,使用inspectdb
命令生成:
class Paises(models.Model):
id_country = models.IntegerField(db_column='ID_COUNTRY', primary_key=True)
country_name = models.TextField(db_column='COUNTRY_NAME', blank=True, null=True)
country_phone_code = models.IntegerField(db_column='COUNTRY_PHONE_CODE', blank=True, null=True)
class Meta:
managed = False
db_table = 'PAISES'
verbose_name_plural = "Paises"
def __str__(self):
return self.country_name
然后这是注册模型的admin类(如文档中所建议的):
class PaisesAdminModel(admin.ModelAdmin):
using = "external"
list_display = ['id_country', 'country_name', 'country_phone_code']
search_fields = ("country_name",)
list_display_links = ('id_country', 'country_name')
def save_model(self, request, obj, form, change):
obj.save(using=self.using)
def delete_model(self, request, obj):
obj.delete(using=self.using)
def get_queryset(self, request):
return super().get_queryset(request).using(self.using)
def formfield_for_foreignkey(self, db_field, request, **kwargs):
return super().formfield_for_foreignkey(
db_field, request, using=self.using, **kwargs
)
def formfield_for_manytomany(self, db_field, request, **kwargs):
return super().formfield_for_manytomany(
db_field, request, using=self.using, **kwargs
)
admin.site.register(Paises, PaisesAdminModel)
然后我运行了python manage.py makemigrations
和python manage.py migrate
,一切似乎都没问题,但随后我发现了以下行为:
- 模型被正确地列出,所有的列和信息都没问题,如果我使用ForeignKey,我甚至可以看到其他模型的名称。
- 我可以删除对象没有问题,该功能似乎工作。(delete_model)
- 我可以编辑现有的模型,甚至使用外键
- 我无法创建新模型
- 我无法从与外键相关的其他模型过滤
当我尝试保存对象时,查看错误跟踪,可以看到错误:Exception Value: relation "PAISES" does not exist LINE 1: SELECT 1 AS "a" FROM "PAISES" WHERE "PAISES"."ID_COUNTRY" = ...
而且它试图使用默认数据库,尽管我指定使用外部数据库
这是完整的stacktrace:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/zonas_geograficas/paises/add/
Django Version: 4.1.7
Python Version: 3.10.6
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'usuarios',
'zonas_geograficas']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
The above exception (relation "PAISES" does not exist
LINE 1: SELECT 1 AS "a" FROM "PAISES" WHERE "PAISES"."ID_COUNTRY" = ...
^
) was the direct cause of the following exception:
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 56, in inner
response = get_response(request)
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/contrib/admin/options.py", line 686, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/utils/decorators.py", line 134, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/views/decorators/cache.py", line 62, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/contrib/admin/sites.py", line 242, in inner
return view(request, *args, **kwargs)
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1891, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/utils/decorators.py", line 46, in _wrapper
return bound_method(*args, **kwargs)
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/utils/decorators.py", line 134, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1751, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1797, in _changeform_view
form_validated = form.is_valid()
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/forms/forms.py", line 205, in is_valid
return self.is_bound and not self.errors
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/forms/forms.py", line 200, in errors
self.full_clean()
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/forms/forms.py", line 439, in full_clean
self._post_clean()
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/forms/models.py", line 498, in _post_clean
self.validate_unique()
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/forms/models.py", line 507, in validate_unique
self.instance.validate_unique(exclude=exclude)
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/db/models/base.py", line 1207, in validate_unique
errors = self._perform_unique_checks(unique_checks)
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/db/models/base.py", line 1317, in _perform_unique_checks
if qs.exists():
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/db/models/query.py", line 1226, in exists
return self.query.has_results(using=self.db)
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/db/models/sql/query.py", line 592, in has_results
return compiler.has_results()
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1366, in has_results
return bool(self.execute_sql(SINGLE))
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1398, in execute_sql
cursor.execute(sql, params)
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 102, in execute
return super().execute(sql, params)
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute
with self.db.wrap_database_errors:
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
Exception Type: ProgrammingError at /admin/zonas_geograficas/paises/add/
Exception Value: relation "PAISES" does not exist
LINE 1: SELECT 1 AS "a" FROM "PAISES" WHERE "PAISES"."ID_COUNTRY" = ...
^
我希望你能看到一些我看不到的东西,提前谢谢你。
回溯第一个答案
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner
self.run()
File "/usr/lib/python3.10/threading.py", line 953, in run
self._target(*self._args, **self._kwargs)
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
autoreload.raise_last_exception()
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception
raise _exception[1]
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 398, in execute
autoreload.check_errors(django.setup)()
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate
app_config.import_models()
File "/home/javif/Documents/GitHub/AdminPanel/venv/lib/python3.10/site-packages/django/apps/config.py", line 269, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/home/javif/Documents/GitHub/AdminPanel/zonas_geograficas/models.py", line 11, in <module>
class Paises(models.Model):
File "/home/javif/Documents/GitHub/AdminPanel/zonas_geograficas/models.py", line 27, in Paises
objects = PaisesManager()
TypeError: Manager.__init__() missing 1 required positional argument: 'rootnode'
1条答案
按热度按时间58wvjzkj1#
.using
是不够的。Django执行unique
检查,忽略了using
。但是,您可以通过覆盖_default_manager
来修复此问题:实际上,Django的许多“机制”都是不知道的。