Listing movies
Let's improve our app. We will display the movie objects stored in the admin database. In movie/views.py
, add the following in bold:
… from .models import Movie def home(request): searchTerm = request.GET.get('searchMovie') movies = Movie.objects.all() return render(request, 'home.html', {'searchTerm':searchTerm, 'movies': movies}) …
Let's look at what's happening in the code. We first import the Movie
model:
from .models import Movie
Then, the previous code grabs all the movie objects from the database (using the all
method) and assigns them to movies
:
movies = Movie.objects.all()
We then pass movies
in the dictionary to home.html
.
Django makes it really straightforward to access objects in the database. If we have to write code to connect to the database, write SQL statements...