我在Django中使用多个数据库,并在settings.py中连接默认的SQLite和PostgreSQL db。
setting.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'
}
}
并且还将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
return False
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
进行迁移时,我得到了这个错误:raise ValueError(cannot assign "%r": the current database router prevents this relation.' % value) ValueError: Cannot assign "<ContentType: config>": the current database router prevents this relation.
发布于 2021-07-12 18:18:48
我已经通过在routers.py文件中添加elif条件更改了allow_relation方法,现在它可以正常工作了。
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 False
https://stackoverflow.com/questions/68344644
复制相似问题