2017-06-14 77 views
1

我使用兩個mysql模式X和Y,它們都包含多個表,但在兩個模式中都有一個表具有相同的名稱。如何在django中使用兩個具有相同名稱的mysql在mysql中的兩個不同模式

兩者的模式如下:

+--------------+--+--------------+ 
| 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單獨查詢兩個表。 任何關於此的幫助/線索都會有所幫助。提前致謝。

+0

你有每個模式的連接?你的'DATABASES'配置如何? –

+0

DATABASES配置如下: '數據庫= { '缺省':{ '發動機': 'django.contrib.gis.db.backends.mysql', 'NAME': 'X', '用戶' :DATABASE_USERNAME, '密碼':DATABASE_PASSWORD, 'HOST':DATABASE_HOST_NAME, '端口': '3306', '選項':{ '字符集': 'utf8mb4'}, } }' 同我的方式將模式Y添加到字典中。 – Shrey

+0

這就是要點。你有兩個數據庫配置?一個'default'和其他'y',例如? –

回答

0

鑑於你DATABASES配置,你可以嘗試:

  1. 更改型號名稱或創建一個新的應用程序具有不同models模塊,對每個方案:

    class YPhoto(models.Model): 
        ... 
    
    class XPhoto(models.Model): 
        ... 
    
  2. 創建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 
    
  3. 路由器添加到settings.py

    DATABASE_ROUTERS = ['myapp.models.MyRouter',] 
    

檢查docs有關數據庫的路由。

+0

糟糕,我注意到你必須檢查'if's中'Y'模式中的所有表。也許你最好爲'Y'架構中的表創建一個新的應用程序 –

+0

謝謝,會試試這個。 – Shrey

+0

我會要求回答我的另一個問題,鏈接如下: https://stackoverflow.com/questions/44496101/how-to-insert-emoji-into-mysql-5-5-and-higher-using- Django的ORM?noredirect = 1#comment75996316_44496101 – Shrey

相關問題