2010-03-24 104 views
5

在開發版本中,Django的新的多數據庫功能,我一直在努力創建一個管理命令,讓我將數據從活動站點同步到開發人員機器進行擴展測試。 (具有實際數據,特別是用戶輸入的數據,可以測試更廣泛的輸入範圍。)Django中的devel/live數據庫之間的數據同步

現在我已經有了一個「主要」工作命令。它可以同步「簡單」模型數據,但我遇到的問題是它忽略ManyToMany字段,我沒有看到它的任何理由。任何人有任何想法如何解決這個問題或更好地處理這個問題?我應該首先將第一個查詢導出到夾具,然後重新導入它?

from django.core.management.base import LabelCommand 
from django.db.utils import IntegrityError 
from django.db import models 
from django.conf import settings 

LIVE_DATABASE_KEY = 'live' 

class Command(LabelCommand): 
    help = ("Synchronizes the data between the local machine and the live server") 
    args = "APP_NAME" 
    label = 'application name' 

    requires_model_validation = False 
    can_import_settings = True 

    def handle_label(self, label, **options): 

     # Make sure we're running the command on a developer machine and that we've got the right settings 
     db_settings = getattr(settings, 'DATABASES', {}) 
     if not LIVE_DATABASE_KEY in db_settings: 
      print 'Could not find "%s" in database settings.' % LIVE_DATABASE_KEY 
      return 

     if db_settings.get('default') == db_settings.get(LIVE_DATABASE_KEY): 
      print 'Data cannot synchronize with self. This command must be run on a non-production server.' 
      return 

     # Fetch all models for the given app 
     try: 
      app = models.get_app(label) 
      app_models = models.get_models(app) 
     except: 
      print "The app '%s' could not be found or models could not be loaded for it." % label 

     for model in app_models: 
      print 'Syncing %s.%s ...' % (model._meta.app_label, model._meta.object_name) 

      # Query each model from the live site 
      qs = model.objects.all().using(LIVE_DATABASE_KEY) 

      # ...and save it to the local database 
      for record in qs: 
       try: 
        record.save(using='default') 
       except IntegrityError: 
        # Skip as the record probably already exists 
        pass 
+0

這是否適用於外鍵? – 2010-03-24 06:50:08

+0

@Ofri - 如果具有該PK的記錄存在,它可以正常工作,但要確保「按順序」創建東西有點困難 – 2010-03-29 17:31:07

+0

那麼對於M2M來說,也許它有同樣的問題?他們必須在兩個模型之後創建。 – 2010-03-30 13:46:08

回答

0

這並不完全回答你的問題,但爲什麼不只是做一個數據庫轉儲和數據庫恢復?

2

Django命令擴展的Dumpscript應該會有很大幫助。

+0

這似乎有一些承諾。我會玩弄它。 – 2010-03-29 17:32:38