【问题标题】:Syncing data between devel/live databases in Django在 Django 中的开发/实时数据库之间同步数据
【发布时间】:2010-03-24 02:10:20
【问题描述】:

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

【问题讨论】:

  • 这对外键有效吗?
  • @Ofri -- 如果存在具有该 PK 的记录,则它可以工作,但确保“按顺序”创建事物有点困难
  • 那么 M2M 可能是同样的问题?它们必须在它们的两个模型之后创建。

标签: django django-orm


【解决方案1】:

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

【讨论】:

  • 这似乎有一些希望。我会玩弄它的。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-21
    • 1970-01-01
    • 2022-12-28
    • 1970-01-01
    • 2021-11-21
    相关资源
    最近更新 更多