I would like to ask how to set models to specific database . I'm still new to django and read about the Database Routing in the Django website, I have 2 models, userMod
and adminMod
.userMod
should go to database userDB.adminMod
should go to database adminDB.
But when I migrated it, both table exist in both database. I already have included app_label
on meta, but its still not working. I am using django 1.8
我想问一下如何为特定的数据库设置模型。我还是django的新手,在django网站上了解了数据库路由,我有两个模型,userMod和adminMod。userMod应该访问数据库userDB。adminMod应该访问数据库adminDB。但是当我迁移它时,两个表都存在于两个数据库中。我已经在meta上包含了app_label,但是它仍然不能工作。我用的是django 1.8
EDIT: I am just trying it on userDB for a while and eventually will use it with adminDB. This is my code:
编辑:我只是在userDB上试用了一段时间,最终会在adminDB上使用它。这是我的代码:
routers.py
routers.py
class router(object):
def db_for_read(self, model, **hints):
if model._meta.app_label == 'userDB':
return 'userDB'
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == 'userDB':
return 'userDB'
return None
def allow_relation(self, obj1, obj2, **hints):
if obj1._meta.app_label == 'userDB' or\
obj2._meta.app_label == 'userDB':
return True
return None
def allow_migrate(self, db, app_label, model=None, **hints):
if app_label == 'userDB':
return db == 'userDB'
return None
2 个解决方案
#1
1
Try this:
试试这个:
class userMod(models.Model):
name = models.CharField(max_length=120)
class Meta:
db_table='userDB'
#2
0
Remember to tell django about your database router in the settings.py
记得在settings.py中告诉django关于数据库路由器的信息。
https://docs.djangoproject.com/en/1.8/topics/db/multi-db/
https://docs.djangoproject.com/en/1.8/topics/db/multi-db/
Search for DATABASE_ROUTERS setting
寻找DATABASE_ROUTERS设置
#1
1
Try this:
试试这个:
class userMod(models.Model):
name = models.CharField(max_length=120)
class Meta:
db_table='userDB'
#2
0
Remember to tell django about your database router in the settings.py
记得在settings.py中告诉django关于数据库路由器的信息。
https://docs.djangoproject.com/en/1.8/topics/db/multi-db/
https://docs.djangoproject.com/en/1.8/topics/db/multi-db/
Search for DATABASE_ROUTERS setting
寻找DATABASE_ROUTERS设置