在Django中同步devel / live数据库之间的数据

时间:2010-03-24 02:10:21

标签: django django-orm

在开发版中使用Django新的多数据库功能,我一直在尝试创建一个管理命令,让我将实时站点的数据同步到开发人员机器以进行扩展测试。 (拥有实际数据,特别是用户输入的数据,可以让我测试更广泛的输入。)

现在我有一个“大多数”工作命令。它可以同步“简单”的模型数据,但我遇到的问题是它忽略了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

2 个答案:

答案 0 :(得分:2)

Django命令扩展的Dumpscript应该会有很多帮助。

答案 1 :(得分:0)

这不能完全回答您的问题,但为什么不进行数据库转储和数据库恢复呢?