1

I would like to use a json file to populate an instance of a Django model. I have essentially flatten the structure in the json to a few table/classes. How do you map the json data to the Django tables?

What is the most efficient ways of doing this?

Thanks.

0

2 Answers 2

2
$ python manage.py loaddata yourjsonfile.json

Let's say you want to populate the standard django user table with 2 users: John Lennon and Yoko Ono. Your json will something like:

[
{
    "pk": 1,
    "model": "auth.user",
    "fields": {
        "username": "john",
        "first_name": "John",
        "last_name": "Lennon",
        "is_active": true,
        "is_superuser": true,
        "is_staff": true,
        "last_login": "2015-06-03T14:07:31.392Z",
        "groups": [],
        "user_permissions": [],
        "password": "pbaasdf_sha256$12001$9Ser7lc1k1pWQFqk0x3u/T6I3",
        "email": "[email protected]",
        "date_joined": "2015-03-10T15:38:34.406Z"
    }
},
{
    "pk": 2,
    "model": "auth.user",
    "fields": {
        "username": "yoko",
        "first_name": "Yoko",
        "last_name": "Ono",
        "is_active": true,
        "is_superuser": false,
        "is_staff": false,
        "last_login": "2015-05-19T13:36:58.444Z",
        "groups": [],
        "user_permissions": [],
        "password": "baasdf_sha256$12cJskLs9Ser7lc1k1pWQFqk0x3u/T6I3",
        "email": "[email protected]",
        "date_joined": "2014-05-19T13:36:58.444Z"
    }
}
]
Sign up to request clarification or add additional context in comments.

2 Comments

How do you use your existing JSON file without having to create a new one?
You can't use it if it does not have the fields that the command 'python manage.py loaddata' accepts. You have to specify for example the name of the model (field "model"). If you don't put it Django will never know where to put those data.
1

"Providing initial data for models"

It’s sometimes useful to pre-populate your database with hard-coded data when you’re first setting up an app. You can provide initial data via fixtures.

A fixture is a collection of data that Django knows how to import into a database. The most straightforward way of creating a fixture if you’ve already got some data is to use the manage.py dumpdata command. Or, you can write fixtures by hand; fixtures can be written as JSON, XML or YAML (with PyYAML installed) documents. The serialization documentation has more details about each of these supported serialization formats.

1 Comment

How do you map the data in the JSON file to the tables? Meaning how doesn't manage.py dumpdata downdata a hierarchical JSON file in to a flat SQL table without specifying the fields it needs to be mapped to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.