JSON Fixture with Foreign Key - How do I import it successfully?

3,929 views
Skip to first unread message

jawspeak

unread,
Jul 20, 2008, 10:41:54 PM7/20/08
to Django users
I don't know how to import a json fixture that uses a foreign key.
Searching the forums and web wasn't helpful for me to find specifics,
so I hoep someone can point out my silly mistake.

Hers's my example json:

[
{"pk": "0", "model": "polls.Choice", "fields": { "choice": "I like
vegetables", "votes": "0"}}
]

But the error I get is:
Problem installing fixture '/Users/admin/projects/django/tutorials/
tutorial1/../tutorial1/polls/fixtures/polls.json':
polls_choice.poll_id may not be NULL

I'm working through the basic tutorial, where the models.py is:

class Choice(models.Model):
poll = models.ForeignKey(Poll, edit_inline=models.STACKED,
num_in_admin=3)
choice = models.CharField(maxlength=200, core=True)
votes = models.IntegerField(core=True)

class Poll(models.Model):
question = models.CharField(maxlength=200)
pub_date = models.DateTimeField('date published')

jawspeak

unread,
Jul 20, 2008, 10:47:56 PM7/20/08
to Django users
Here's a trick:

use the manage.py dumpdata command to see what the existing format is!

[
{
"pk": "1",
"model": "polls.poll",
"fields": {
"pub_date": "2008-07-20 17:44:31",
"question": "TEST 1"
}
},
{
"pk": "1",
"model": "polls.choice",
"fields": {
"votes": 1,
"poll": 1,
"choice": "choice1"
}
},
{
"pk": "2",
"model": "polls.choice",
"fields": {
"votes": 23,
"poll": 1,
"choice": "choice2"
}
}
]


that solves it, instead of having the poll_id manually, i just need to
have the field "poll" reference back to the poll_id

jawspeak

unread,
Jul 20, 2008, 10:49:34 PM7/20/08
to Django users
>   {"pk": "0", "model": "polls.Choice", "fields": { "choice": "I like
> vegetables", "votes": "0"}}

also, fyi, it looks like primary keys have to start at 1
Reply all
Reply to author
Forward
0 new messages