I have been using a Django database for a while without any major issues. Today I needed to set default values for a few tables for the first time. I created a fixtures directory in the top-level Django directory. Then I created the files for the default values. However, I keep getting error messages and I'm not sure why.
First I tried to use .sql files. It is worth noting that these tables are very simple; they only have one value, "name". My SQL file looked like this:
INSERT INTO MyTable (name) VALUES ('Default');
I saved this as MyTable.sql
. When I ran the command python manage.py loaddata fixtures/MyTable.sql
, I got this error message:
CommandError: Problem installing fixture 'MyTable': sql is not a known serialization format.
(Note: I also tried without the fixtures/ part, for the above example and the next, and got identical results).
I asked my project lead and he said he doesn't think SQL files can be used for this. So, I tried JSON files. My MyTable.json
looked like this:
[
{
"model": "mydatabase.MyTable",
"pk": 1,
"fields": {
"name": "Default"
}
}
]
I'll be very upfront to admit I've never worked with JSON in this context before, only in web development, so I don't know if the issue may be something I'm doing wrong here. I tried to base it on the formatting I found here. When I ran this through the loaddata function again, I got this error message:
C:\Python27\lib\site-packages\django-1.6.1-py2.7.egg\django\core\management\commands\loaddata.py:216: UserWarning: No fixture named 'fixtures/MyTable' found.
This is my first time doing this and I've had a bit of a hard time finding documentation to figure out what I'm doing wrong. Could anyone please offer advice? Thanks!
To create your fixture files start with an empty database and then add some data to your database using the djanog-admin or the django shell or even pure SQL. After that you can do a
python manage.py dumpdata # to dump all your data, or python manage.py dumpdata app_name # to dump all data of a specific app, or python manage.py dumpdata app_name.model_name # to dump all data of a specific model
The above will print data to your stdout. In order to write it to a file use a redirect (>), for instance
python manage.py dumpdata auth.User > user_fixture.json
Update: I just saw that you are using Windows -- remember to load your fixtures using a backslash (\
).