导出
执行./manage.py dumpdata -a > data.json
即可完成导出
导入
1. ./manage.py loaddata 的方式导入
优点:
* 方便,不容易出问题
缺点:
* 性能慢
2. 自定义脚本导入
from collections import defaultdict
from django.core import serializers
from django.db import transaction
from django.db.models import sql
from django.db import connections
connection = connections['default']
obj_dict = defaultdict(dict)
deserialized = serializers.deserialize('json', open('/data/chat.json'))
# organize by model class
for item in deserialized:
obj = item.object
if obj._meta.app_label == 'chat':
obj_dict[obj.__class__][str(obj.pk)] = obj
with transaction.atomic():
for cls, objs in obj_dict.items():
# cls.objects.bulk_create(objs)
fields = cls._meta.local_concrete_fields
query = sql.InsertQuery(cls)
query.insert_values(fields, objs.values())
query.get_compiler(connection=connection).execute_sql()
其他
跨数据库迁移
pgloader
pgloader \
--debug \
pgsql://source:5432/chat \
pgsql://target:5432/chat_test