1

I want to load below json data in my Model.

{
    "99popularity": 79.0,
    "director": "William Cottrell",
    "genre": [
      "Animation",
      " Family",
      " Fantasy",
      " Musical",
      " Romance"
    ],
    "imdb_score": 7.9,
    "name": "Snow White and the Seven Dwarfs"
  },
  {
    "99popularity": 84.0,
    "director": "Stanley Kubrick",
    "genre": [
      "Adventure",
      " Mystery",
      " Sci-Fi"
    ],
    "imdb_score": 8.4,
    "name": "2001 : A Space Odyssey"
  },

I have create two models using reference to json data

class Genre(models.Model):
    name = models.CharField(max_length=30)

class Movie(models.Model):
    popularity = models.FloatField(max_length=10)
    director = models.CharField(max_length=30)
    genre = models.ManyToManyField(Genre)
    imdb_score = models.FloatField(max_length=10)
    name = models.CharField(max_length=30)

But in Genre Model i don't have any data and in json in genre section their is no id instead name. How can i load that data in my model. Please Help.

6
  • What do you have so far? Commented Mar 13, 2019 at 14:06
  • right now i am trying to read json file and trying to convert 99popularity because it is not valid field name in django model Commented Mar 13, 2019 at 14:14
  • When you say you want to load the json into the db what do you mean? Is that inside a migration file to load this once? Or in a view where you process the json? Or are you talking about manage.py loaddata? Commented Mar 13, 2019 at 14:19
  • @dirkgroten in a view where you process the json Commented Mar 13, 2019 at 14:20
  • Then show us the code you have till now, so we can see what’s not working. Commented Mar 13, 2019 at 14:26

1 Answer 1

5

You can use the get_or_create method, but you have to make the name field unique. To create two models using reference to json data, I would use a custom class method like this:

class Genre(models.Model):
    name = models.CharField(max_length=30, unique=True)  # make unique

class Movie(models.Model):
    popularity = models.FloatField(max_length=10)
    director = models.CharField(max_length=30)
    genre = models.ManyToManyField(Genre)
    imdb_score = models.FloatField(max_length=10)
    name = models.CharField(max_length=30)


    @classmethod
    def create(cls, **kwargs):
        movie = cls.objects.create(
            popularity=kwargs['99popularity'],
            director=kwargs['director'],
            imdb_score=kwargs['imdb_score'],
            name=kwargs['name']
        )
        for genre_name in kwargs['genre']:
            genre, created = Genre.objects.get_or_create(name=genre_name)
            movie.genre.add(genre)
        return movie

Assuming you converted your json data to a string you can do this:

import json
from .models import Movie

# you can also keep this inside a view
with open('movie_data.json', encoding='utf-8') as data_file:
    json_data = json.loads(data_file.read())

    for movie_data in json_data:
        movie = Movie.create(**movie_data)
        # movie and genres created
Sign up to request clarification or add additional context in comments.

4 Comments

Your code gave me good idea how to do it. I am confused how to load that json data. because i am not using fixture
If you have a json file you can use this question on how to convert it to a dict stackoverflow.com/questions/2835559/…
Thanks you understood my actual question. This was my first time to play with json file in Python
@gormih yes, you can use bulk_create for big datasets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.