I have a model for movies in my django project:
class Movie(models.Model):
title = models.CharField(max_length=128, blank=False)
description = models.TextField()
movie_length = models.CharField(max_length=20)
director = models.CharField(max_length=50)
rating = models.FloatField(validators=[MinValueValidator(0.0),MaxValueValidator(10.0)])
created_at = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to='movie_img/')
category = models.CharField(max_length=50)
I want to fill the database using python API wrappers for themoviedb.org API like this https://github.com/celiao/tmdbsimple/ or https://github.com/wagnerrp/pytmdb3/. But i am not sure how to do this. I just want to put around 100 movies at one go without having to add every movie one by one. How can i do this, please help. Thank you.
First you will have to read the data from the API into Python objects. Assume you now have a list L of tuples, each tuple is a record of a movie.
Your script could be load_from_api.py
#!/usr/bin/env python
import os
import sys
# ... read the data from the API
# ... so L = [("movie title","movie description..."),("movie2 title",..)]
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings"
import django
django.setup()
from yourapp.models import Movie
for movie in L:
m = Movie(title=movie[0],
description=movie[1],
...
)
m.save()
Then simply run the script. Note that you could load the data directly to the DB with SQL, but that is not recommended since this ignores the django models rules, defaults, validations, signals etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With