我正在使用两个mysql模式X和Y,它们都包含多个表,但是在两个模式中都有一个名称相同的表。
两种模式如下:
+--------------+--+--------------+
| X | | Y |
+--------------+--+--------------+
| name | | album_info |
+--------------+--+--------------+
| invite | | photo_info |
+--------------+--+--------------+
| photo | | photo |
+--------------+--+--------------+
| user_details | | temp |
+--------------+--+--------------+
现在,我想查询两个表,但是当我用相同的名称在models.py文件中写入表结构时,会引发错误/异常。
我在routers.py文件中声明了两个表,如下所示:
modelDatabaseMap = {
.
'photo': 'default',
.
.
.
'photo': 'y',
}
(X是我的默认架构)。
声明我的models.py如下:
class Photo(models.Model):
id = models.AutoField(db_column='ID', primary_key=True)
has_tagged_with = models.IntegerField()
has_reposted_with = models.IntegerField()
.
.
class Meta:
managed = False
db_table = 'photo'
class Photo(models.Model):
id = models.AutoField(db_column='ID', primary_key=True)
account_id = models.IntegerField()
p_id = models.IntegerField()
is_profile = models.IntegerField()
.
.
class Meta:
managed = False
db_table = 'photo'
现在,歧义首先是名称,在models.py中是声明,其次是在查询中。
我被困在如何通过orm在两个表上分别查询。关于此的任何帮助/线索都将有所帮助。提前致谢。
最佳答案
给定您的DATABASES
配置,您可以尝试:
更改模型名称或为每个架构使用不同的models
模块创建新应用:
class YPhoto(models.Model):
...
class XPhoto(models.Model):
...
创建一个
router.py
模块:class MyRouter(object):
def db_for_read(self, model, **hints):
if model.__name__ == 'YPhoto':
return 'Y'
return None
def db_for_write(self, model, **hints):
if model.__name__ == 'YPhoto':
return 'Y'
return None
def allow_relation(self, obj1, obj2, **hints):
# Maybe you want to prevent relations between different schemas, it's up to you
return True
def allow_syncdb(self, db, model):
return True
将路由器添加到
settings.py
:DATABASE_ROUTERS = ['myapp.models.MyRouter',]
检查关于数据库路由的docs。
关于mysql - 如何在带有Django的MySQL中的两个不同架构中使用两个具有相同名称的表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44538316/