See part 1 here.
In this part we are discussing what to do when we add custom user model later in the project.
Note that in this scenario, we are in a very non-ideal situation. To keep unknown surprises at the minimum, we will still delete old database but we will use the concept of fixtures to save as much information as we can from the current database, that can be reused later.
For example, if we have an eCommerce site with a lot of products and their details in the database, we can save this info as this is not really connected to any specific user. Then we can remove the database, let Django create a new database with the new custom user model and then you can bring in the products and their details saved earlier. All this is possible using fixtures.
If you want to dump entire database as json, this is the fixture for it:
python manage.py dumpdata --format json --indent 4
The above will dump all the info to the console. You can save all this into a file like so:
python manage.py dumpdata --format json --indent 4 > all_database.json
The above line will create an all_database.json file at the root of project wih all the database content in it.
I generally like to make my dumps separately for specific tables. Like if I have an app called “ecom_product” and in its models.py file, I have a model called Product, I will save this specific model like so:
Create a directory called “fixtures” in the app folder “ecom_product”. Then run this command
python manage.py dumpdata ecom_product.Product --format json --indent 4 > ecom_product/fixtures/ecom_product.json
Bingo!, you have dumped all the data from your Products table.
Now, goto part-1. And do steps 1 through 3. Then delete/move the old database so Django can create a new one. Before running step 4, remove all migrations. To do this, goto each app’s migrations folder and remove everything except __init__.py file (Also remove __pycache__ folder inside migrations folder). In reality, you only need to remove the migrations related to the old user model. I remove all migrations just in case.
Now you can go ahead with steps 4 and onwards.
Do all the migrations.
Recreate superuser (this time using email). Goto admin panel to see all looks good.
Then at last we are ready to load the saved dumps back into the new database.
Here is how to load dumps back into the database.
python manage.py loaddata ecom_product/fixtures/ecom_product.json