Alex Rivera | Logout

How to import a json file to a Django model?

Asked 2012-03-10T02:02:05.470
19

I have a file in json format, with a structure like this?

{
    "Admiralty Islands": [
        [
            "Up to 1 kg",
            "5.00"
        ], 
        [
            "1 - 10 kg", 
            "10.00"
        ], 
    ], 
    "Afghanistan": [
        [
            "Up to 1 kg",
            "15.00"
        ], 
        [
            "1 - 10 kg", 
            "20.00"
        ], 
    ], 
...
}

And three models:

class Country(models.Model):
    name = models.CharField(max_length=128, unique=True)

class Weight(models.Model):
    name = models.CharField(max_length=128, unique=True)
    min_weight = models.IntegerField()
    max_weight = models.IntegerField()

class Shipping(models.Model):
    country = models.ForeignKey(Country)
    weight = models.ForeignKey(Weight)
    price = models.DecimalField(max_digits=7, decimal_places=2)

What is the best way to import to the database using a json file?

Should I convert the json file into a fixture file? If so, how do I handle the relationships between tables?

Or is it better to write the view like:

f = open('file.json', 'r')
obj = simplejson.load(f)

for o in obj:
    record = Country(name = o)
    record.save()

But I also cannot figure out how to make relations between the models.

Or is there an easier way?

Thanks.

Edit
Report

1 Answer

28

Use manage.py to import fixtures:

python manage.py loaddata fixture.json
answered 2012-10-15T13:39:00.717

Your Answer