我在 Django 中使用了多个数据库,并在 settings.py 中连接了默认的 SQLite 和 PostgreSQL 数据库。
设置.py:
DATABASE_ROUTERS = ['routers.db_routers.AppRouter']
DATABASE_APPS_MAPPING = {'product': 'postgres',}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
},
'postgres': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'product',
'USER': 'postgres',
'PASSWORD':'password',
'HOST':'localhost'
}
}
并在 routers 文件夹中创建了 db_routers.py:
class AppRouter:
"""
A router to control all database operations on models in the
product application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read user models go to postgres.
"""
if model._meta.app_label == 'product':
return 'postgres'
return 'default'
def db_for_write(self, model, **hints):
"""
Attempts to write user models go to postgres.
"""
if model._meta.app_label == 'product':
return 'postgres'
return 'default'
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the user app is involved.
"""
if obj1._meta.app_label == 'product' or \
obj2._meta.app_label == 'product':
return True
elif 'product' not in [obj1._meta.app_label, obj2._meta.app_label]:
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
Make sure the auth app only appears in the 'product_db'
database.
"""
if app_label == 'product':
return db == 'postgres'
return None
这里是model.py:
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
weight = models.DecimalField(max_digits=10, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
app_label = 'product'
def __str__(self):
return self.name
我通过运行 python3 manage.py makemigrations
成功制作了表格,但是当我尝试使用 python3 manage.py migrate --database=postgres
进行迁移时,我收到此错误: ProgrammingError: relation "product" does not exist. SELECT COUNT(*) AS "__count" FROM "product"
并且该表格也不存在于 PgAdmin 中。
产品的迁移.py:
# Generated by Django 3.2.5 on 2021-07-16 13:25
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Product',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('price', models.DecimalField(decimal_places=2, max_digits=10)),
('weight', models.DecimalField(decimal_places=2, max_digits=10)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
],
options={
'db_table': 'product',
'managed': False,
},
),
]
错误:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/api/product/
Django Version: 3.2.5
Python Version: 3.8.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'post',
'product']
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/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
The above exception (relation "product" does not exist
LINE 1: ...product"."created_at", "product"."updated_at" FROM "product"
^
) was the direct cause of the following exception:
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/rest_framework/generics.py", line 239, in get
return self.list(request, *args, **kwargs)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/rest_framework/mixins.py", line 46, in list
return Response(serializer.data)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/rest_framework/serializers.py", line 745, in data
ret = super().data
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/rest_framework/serializers.py", line 246, in data
self._data = self.to_representation(self.instance)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/rest_framework/serializers.py", line 663, in to_representation
return [
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/db/models/query.py", line 280, in __iter__
self._fetch_all()
File "/home/rudrakshi/Desktop/Rose/assignment/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/rudrakshi/Desktop/Rose/assignment/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/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql
cursor.execute(sql, params)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute
return super().execute(sql, params)
File "/home/rudrakshi/Desktop/Rose/assignment/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/rudrakshi/Desktop/Rose/assignment/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/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/rudrakshi/Desktop/Rose/assignment/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/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
Exception Type: ProgrammingError at /api/product/
Exception Value: relation "product" does not exist
LINE 1: ...product"."created_at", "product"."updated_at" FROM "product"
^
运行 makemigrations 然后迁移后, 我运行我的服务器,当我到达端点时 - 'api/product/' 我收到这个错误 - 关系“product”不存在 LINE 1: ...product"."created_at", "product"."updated_at" FROM “产品”
答案 0 :(得分:0)
看看您的迁移文件,您有 'managed': False,
,这是什么意思?这意味着您不希望迁移系统管理此模型。这意味着运行 migrate
不会导致在数据库中创建相应的表。 除非您了解自己在做什么,否则不要编辑迁移文件!
删除您可能对迁移文件所做的任何更改,尤其是 'managed': False,
,然后运行:
python manage.py migrate product zero --fake
这将导致 Django 将应用“产品”的所有迁移标记为未应用。这很好,因为这似乎是您的初始迁移,否则您可能希望将 zero
更改为某个迁移名称。下一次运行:
python manage.py migrate