Django loaddata实例位于数据库“postgres”上,值位于数据库“default”上

2024-10-01 02:38:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从sqlite3迁移到postgres。整个数据库的dumpdata不工作,所以我一个接一个地做。问题是,当我尝试加载users时,它会引发错误:

ValueError: Problem installing fixture '/.../dbmig/auth.user.json': Could not load auth.User(pk=1): Cannot add "<Group: contractor>": instance is on database "postgres", value is on database "default"

这不是真的,因为groups是在用户之前迁移的

我创建了一个我使用的命令:

def dumpload(model):
    json_filename = model+'.json'

    DBMIG_DIR = os.path.join(settings.BASE_DIR, 'dbmig')
    json_filepath = os.path.join(DBMIG_DIR,json_filename)

    with open(json_filepath, 'w') as f:
        call_command('dumpdata', model, stdout=f, database='default')

    call_command('loaddata', json_filepath, database='postgres')

class Command(BaseCommand):

    def handle(self, *args, **options):
        dumpload('auth.group')
        dumpload('auth.user')

编辑

这没有意义,这些组已经在postgresdb中了。我在两个命令之间添加了print(Group.objects.using('postgres').values('pk')),我可以清楚地看到这些组位于postgres数据库中,并且它们具有正确的ID

这是输出:

Installed 2 object(s) from 1 fixture(s)
<QuerySet [{'pk': 1}, {'pk': 2}]>
error...

编辑-设置.数据库

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    },
    'postgres': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'OPTIONS': {
        },
        'NAME': config.get('db', 'name'),
        'USER': config.get('db', 'user'),
        'PASSWORD': config.get('db', 'password'),
        'HOST': config.get('db', 'host'),
        'PORT': config.get('db', 'port'),
    }
}

Tags: authconfig数据库jsondefaultdbgetmodel