Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 file so it couldn't match them with there moods.

like image 647
Nachshon Schwartz Avatar asked May 30 '11 22:05

Nachshon Schwartz


1 Answers

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

like image 121
Timmy O'Mahony Avatar answered Sep 25 '22 17:09

Timmy O'Mahony