Django将对象从一个数据库移动到另一个数据库

时间:2016-02-27 11:43:09

标签: python django postgresql sqlite django-models

尝试SQLite内置命令postgreSQL here

后,我尝试从Django迁移到dumpdata

在官方文档中找到了另一种方式,数据迁移时没有任何错误,但当我尝试通过shell or form保存任何模型的实例时,我收到pk已存在错误。某种程度上django并不了解现有的价值观。 。 。 。

for firm in models.Firm.objects.using("olddb").all():
    firm.save(using="default")

现在default database包含olddb

中的所有对象
>>> Firm.objects.all()[0]
<Firm: ABC>
>>> Firm.objects.all()[0].id
1
>>> f = Firm()
>>> f.name = "ABDEGVHG"
>>> f.save(using="default")
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Users\vaibh\envs\py3\lib\site-packages\django\db\models\base.py", line 590, in save
    force_update=force_update, update_fields=update_fields)
  File "C:\Users\vaibh\envs\py3\lib\site-packages\django\db\models\base.py", line 618, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "C:\Users\vaibh\envs\py3\lib\site-packages\django\db\models\base.py", line 699, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "C:\Users\vaibh\envs\py3\lib\site-packages\django\db\models\base.py", line 732, in _do_insert
    using=using, raw=raw)
  File "C:\Users\vaibh\envs\py3\lib\site-packages\django\db\models\manager.py", line 92, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\vaibh\envs\py3\lib\site-packages\django\db\models\query.py", line 921, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "C:\Users\vaibh\envs\py3\lib\site-packages\django\db\models\sql\compiler.py", line 920, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\vaibh\envs\py3\lib\site-packages\django\db\backends\utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "C:\Users\vaibh\envs\py3\lib\site-packages\django\db\utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "C:\Users\vaibh\envs\py3\lib\site-packages\django\utils\six.py", line 549, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\vaibh\envs\py3\lib\site-packages\django\db\backends\utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: duplicate key value violates unique constraint "girvi_firm_pkey"
DETAIL:  Key (id)=(1) already exists.

有人可以告诉我如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

在#django上由SELECT setval('girvi_firm_id_seq', max(id)) FROM girvi_firm; @ apollo13解决了它IRC建议我更新序列并且它有效。谢谢他