vlad
vlad

Reputation: 855

How to import a json file to a Django model?

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.

Upvotes: 19

Views: 34351

Answers (4)

Yugal Jindle
Yugal Jindle

Reputation: 45716

Well for data in json to be populated to the 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 use fixtures.

  • For mapping Django Serialization is the way to GO.

Upvotes: 2

miki725
miki725

Reputation: 27861

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 it manually goes through all of the json and creates 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.

Upvotes: 3

hlongmore
hlongmore

Reputation: 1856

Django has evolved a lot since this question was asked. Under Django 2.x, probably the best way with the least number of introduced dependencies is to use Django's built-in serializers (as mentioned by @miki725) and data migrations. This will allow your data to get loaded whenever you run migrations (including when migrations are run before running unit tests).

Upvotes: 1

Douwe van der Meij
Douwe van der Meij

Reputation: 1140

Use manage.py to import fixtures:

python manage.py loaddata fixture.json

Upvotes: 26

Related Questions