Simply add (and export) data from your Django database with YAML (3 mins) 🧮

Photo of Tom Dekan
by Tom Dekan

Adding initial data to your Django database and exporting is very simple with Django's in built management commands, loaddata and dumpdata.

In 3 minutes, we'll:

a) produce a super simple Django app, and b) show how to import and export our data into any Django database.

For more context, I used the technique below to add initial data to a Django and HTMX quiz app here: Create a quiz app in 6 minutes with HTMX and Django ☑️

Let's start 🚀

Create a Django project and app

pip install django pyyaml
django-admin startproject core .
python manage.py startapp sim

Add sim to INSTALLED_APPS in core/settings.py:

# core/settings.py

INSTALLED_APPS = [
    # ...
    'sim',
    # ...
]

Create a model

Add the following to sim/models.py:

from django.db import models


class Product(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)

    def __str__(self):
        return self.name

Run the migrations:

python manage.py makemigrations
python manage.py migrate

Load data into your Django database

  • Create a file called product_data.yaml suffix in your root folder and add the following to it:
- model: sim.product
  pk: 1
  fields:
    name: "Chair"
    description: "A mahogany chair"
    price: 49.99
- model: sim.product
  pk: 2
  fields:
    name: "Table"
    description: "An oak table"
    price: 99.99
  • Run the management command to load your data straight into the database:
python manage.py loaddata sim product_data.yaml

You should see the following output:

Installed 2 object(s) from 1 fixture(s)

The data is now in your database. Let's check it out by logging into the Django admin.

Create a superuser

python manage.py createsuperuser
  • Enter the username, email, and password for the superuser.

Show the data in the Django admin

  • Register the Product model by adding the below to sim/admin.py:
from django.contrib import admin
from .models import Product

admin.site.register(Product)
  • Run the server:
python manage.py runserver

Click to on the Product model to see the data. You should see something like this:

Export the data from your Django database

Now imagine that you have some data that you want to export, to then import into another database. This situation typically arises for me when I've added some data to my local database that I want to import into my production database.

  • To export the data to a YAML file, simply run the following command:
python manage.py dumpdata sim.product --natural-foreign --exclude=contenttypes --exclude=auth.permission > product_data1.yaml

We use the --natural-foreign flag to use natural keys for foreign keys. This makes the YAML file more human-readable. We exclude the contenttypes and auth.permission tables because they are not relevant to our data.

Then re-import this data into another database using the loaddata command as above. Simple!

Complete ✅

That's it — it's quick to do as I mentioned. You've now learned how to import and export data from your Django database. 🎉

If you'd like more context, I recently used the technique to add initial data to a Django + HTMX quiz app here: Create a quiz app in 6 minutes with HTMX and Django ☑️

P.S - Build your Django frontend even faster

I want to release high-quality products as soon as possible. Probably like you, I want to make my Django product ideas become real as soon as possible.

That's why I built Photon Designer - an entirely visual editor for building Django frontend at the speed that light hits your eyes. Photon Designer outputs neat, clean Django templates 💡

Let's get visual.

Do you want to create beautiful frontends effortlessly?
Click below to book your spot on our early access mailing list (as well as early adopter prices).
Copied link to clipboard 📋

Made with care by Tom Dekan

© 2024 Photon Designer