首页 > 解决方案 > 如何在django中将变量保存到mysql数据库中

问题描述

所以我从电影网站中提取了数据并将其保存到变量中,例如标题,但现在我正在努力将这些数据发送到 MySQL DB

def index(request):
    response = requests.get(
    'https://fmovies.to/api/list_movies.json',
     params={'limit':'20'},
    )

    json_response = response.json()
    movies = json_response['data']['movies']

    #title = movies[0]['title']
    #movie_url = movies[0]['url']
    #description = movies[0]['description_full']
    #movie_torrent_link = movies[0]['torrents'][0]['url'] 
    #cover_image = movies[0]['medium_cover_image']
    
    for value in movies:
        title = value['title']
        movie_url = value['url']
        description = value['description_full']
        movie_torrent_link = value['torrents'][0]['url']
        image = value['medium_cover_image']
        rating = value['rating']
        genre = value['genres']
        runtime = value['runtime']
        year_of_production = value['year']
        slug = value['slug']
        print(image)
        print(rating)
        print(runtime)
        print(year_of_production)
        print(slug)
    return render(request, 'index.html',{'title':title})

标签: django

解决方案


设法直接保存而没有走很长的路

def index(request):
    response = requests.get(
    'https://fmovies.to/api/list_movies.json',
     params={'limit':'20'},
    )

    json_response = response.json()
    movies = json_response['data']['movies']

    for value in movies:
        save_to_db = Movie.objects.create(
        title=value['title'],
        description = value['description_full'],
        image = value['medium_cover_image'],
        category = value['genres'],
        year_of_production = value['year'],
        movie_url = value['url'],
        movie_torrent_link = value['torrents'][0]['url'],
        rating = value['rating'],
        runtime = value['runtime'],
        )
        save_to_db.save()
    return render(request, 'index.html',)

推荐阅读