I am having trouble accessing a list of data on a through table. The through table is called Cast and has a ManyToManyField for my Movie table (which lists every movie in the database) and another ManyToManyField for my Person table (which lists every actor).
The fields need to be ManyToMany because an actor can appear in many different movies, and a movie can contain many different actors.
I want to run a for-loop that lists all of the actors associated with a given movie (filtered by the movies primary key) and displays them on a web page. So far I cannot list anything on the web page (Movie.title displays the title, but I can't display anything from the Cast table.)
I have tried reading all the other related stackoverflow solutions (such as listing objects from ManyToManyField) but I still cannot get the actor's names to display on the website.
/Model.py
class Movie(models.Model):
title = models.CharField(max_length=250)
class Person(models.Model):
name = models.CharField(max_length=100)
class Cast(models.Model):
movie = models.ManyToManyField(
Movie,
)
castmember = models.ManyToManyField(
Person
)
/View.py
class MoviePageView(TemplateView):
template_name = '_movie_info.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['movie'] = Movie.objects.all()
context['cast'] = Cast.objects.filter(movie__id=**kwargs)
I have also tried:
context['cast'] = Cast.objects.filter(movie__id=self.movie.id)
context['cast'] = Cast.objects.filter(movie__id=**kwargs)
context['cast'] = Cast.objects.all()
/URL.py
urlpatterns = urlpatterns = [
path("<int:pk>", MovieDetailView.as_view(), name="movie_detail"),
]
html page
<div>{{ movie.title }}</div>
{% for info in cast.castmember.all %}
<div>{{ info.name }}</div>
{% endfor %}