5

在开发版本中使用 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
4

2 回答 2

2

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

于 2010-03-24T10:57:16.013 回答
0

这并不能准确回答您的问题,但为什么不直接进行数据库转储和数据库恢复呢?

于 2010-03-24T02:57:31.837 回答