我想在模型中加载json数据以下。
{
"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"
},
我已经通过引用json数据创建了两个模型
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)
但是在Genre
模型中我没有任何data
,在流派部分的json
中,他们不是id
而是name
。如何在我的模型中加载该数据。请帮忙。
答案 0 :(得分:1)
您可以使用get_or_create方法,但是必须使名称字段唯一。要使用对json数据的引用来创建两个模型,我将使用类似这样的自定义类方法:
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
假设您将json数据转换为字符串,则可以执行以下操作:
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