Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import json file to Django model

I have a file in json format, with such a structure:

{
    "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 a 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 most correct way to import to the database using a json file?

Should I convert the json file into fixture file? But what to do with 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 also can not figure out how to make relations between the models.

Or is there an easier way?

Thanks.

like image 735
vlad Avatar asked Mar 10 '12 02:03

vlad


3 Answers

Use manage.py to import fixtures:

python manage.py loaddata fixture.json
like image 79
Douwe van der Meij Avatar answered Oct 20 '22 06:10

Douwe van der Meij


I don't see a very clear structure in your json in a sense that it is not explicitly defined anywhere which field should go into which model and how everything is related. So I would recommend just to make an import script in which manually go through all of the json and create the proper model instances.

A good example in my opinion of well structured json is the output of the Django serialization. You can take a look at it here.

like image 3
miki725 Avatar answered Oct 20 '22 08:10

miki725


Well for data in json to be populated to database:

  • You need to map the data fields from json to the database.

  • The best and the preferred or rather the designed way of doing this is to do use fixtures.

  • For mapping Django Serialization is the way to GO.

like image 2
Yugal Jindle Avatar answered Oct 20 '22 06:10

Yugal Jindle