I have a project created with poetry: poetry new little-bits-of-buddha. It was a very basic Flask app that returned a random bit of JSON from a data.json file. Now I want to ingest the JSON into a database. I picked Django for its ORM and because there was a big community behind it and a great book, “Django for Beginners”.
I created the django project with django-admin startproject little_bits_of_buddha .
Here’s what my project looks like after:
x exa --tree
.
├── little_bits_of_buddha
│ ├── __init__.py
│ ├── app.py
│ ├── asgi.py
│ ├── data.py
│ ├── data.json
│ ├── settings.py
│ ├── shim.py
│ ├── urls.py
│ └── wsgi.py
├── main
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ │ ├── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── manage.py
├── poetry.lock
├── pyproject.toml
├── README.org
└── tests
├── __init__.py
Now, I want to make my first Django app, which I do from the root project directory like the other commands:
python3 manage.py startapp main
Since my dumb app is so small, we can recreate the entire logic from python manage.py shell
import json
from importlib import resources
with resources.open_text("little_bits_of_buddha", "data.json") as json_file:
data = json.load(json_file)
from django.db import models
class Collection(models.Model):
models.JSONField(data)
which returns:
...
130 if app_config is None:
131 if not abstract:
--> 132 raise RuntimeError(
133 "Model class %s.%s doesn't declare an explicit "
134 "app_label and isn't in an application in "
RuntimeError: Model class __main__.Collection doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
If I’m interpreting this correctly, the app isn’t listed in INSTALLED_APPS but here it is:
INSTALLED_APPS = [
"main.apps.MainConfig",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]
My tree looks fairly similar to the mataroa project.
My question:
- Can I import an entire nested JSON object into a Django model like I’ve demonstrated and have the ORM create it in the corresponding Postgres database? I want to preserve the data.json file as the final arbiter of truth.