Cipher
Cipher

Reputation: 2122

How to Load JSON Data in Django Model

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.

Upvotes: 1

Views: 9039

Answers (1)

p14z
p14z

Reputation: 1810

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

Upvotes: 5

Related Questions