How to create initial_data Json fixture for many-to-many relation?
I am creating an initializing file for for my django project database. I am doing this using a file called initial_data.json
which i have created. For example the following code (when syncdb
is run) creates in the model Word
a new row where name="apple"
:
[ { "model": "sites.word", "pk": 1, "fields": { "name": "apple" } } ]
I have managed to this so far for several models, the problem is with models that have a many-to-many field. I've looked around for the correct way to do this and have come up empty.
So, for example, if a Model
mood has many Interests
how would I write in the Json file that mood-1's interests are interest-1, interest-2 and interest-3.
What is the proper way to write in Json a models many-to-many relation?
EDIT:
@pastylegs solution was correct, I was just having trouble because the numbering of my interests was off in the Json fil开发者_StackOverflow中文版e so it couldn't match them with there moods.
I'm pretty sure the manytomany field of your model can be written like a simple list:
[
{
"model": "sites.word",
"pk": 1,
"fields": {
"name": "apple",
"my_m2m_field_name": [1,2,3],
}
}
]
where 1, 2, 3 are the primary keys for the relations
what I like to do is use the dumpdata command. I fire up a test site, use the admin form or the app itself to add just the data that I want to use in my fixture, then I run
./manage.py dumpdata appname > appname/fixtures/initial_data.json
You can dump all the apps together if you leave out appname but I like to do it separately for each model.
If you're using 1.3 (I'm not yet) then you can use --exclude
to not dump some parts. I've aslo seen there is a --indent
option to make the output pretty (just found that now while answering your question).
It's one of those things that's easy to miss in the documentation. ;-)
精彩评论