Dump and Load Data in Django Django.How

Author avatar wrote on 31/05/2022

Entire database

Dump
python manage.py dumpdata > db_data.json
Load
python manage.py loaddata db_data.json

One Table

Dump
python manage.py dumpdata app_label.ModelName > specific_file.json
Load
python manage.py loaddata specific_file.json

Example:

Dump Table Data
python manage.py dumpdata company.CompanyLanguage > langs.json
Load Table Data
python manage.py loaddata langs.json

Exporting Data to be loaded to another Data Base

DB with data
python manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json
New DB
python manage.py flush

// Important disable all signals on models pre_save and post_save

python manage.py loaddata db.json

// Enable all signals on models pre_save and post_save again

Reset DB / delete all tables


1.
pip install django-extensions

2.
INSTALLED_APPS = (
    ...
    'django_extensions',
)

3.
manage.py reset_db

 

Dump Parameters

--all, -a
Uses Django’s base manager, dumping records which might otherwise be filtered or modified by a custom manager.

–format FORMAT

Specifies the serialization format of the output. Defaults to JSON. Supported formats are listed in Serialization formats.
--indent INDENT
Specifies the number of indentation spaces to use in the output. Defaults to None which displays all data on single line.
--exclude EXCLUDE, -e EXCLUDE
django-admin dumpdata --exclude=auth --exclude=contenttypes

Clear data from a table (shell)

python manage.py shell
from {app_name}.models import {model_name}
{model_name}.objects.all().delete()
Resources
CRUDgen Django CRUD generator