[Answer]-Django get query value with manytomanyfield through

1πŸ‘

{% for theater in movie.movietheater_set.all %}
   {% for showtime in theater.theater.all %}
       {{ showtime.time }}
   {% endfor %}
{% endfor %}

It’s confusing because of the related names. related name is the name the oposite entity will access the one where it is defined.

If you do:

class MovieShowtime(models.Model):
    theater = models.ForeignKey(MovieTheater, null=True, related_name='showtimes' )
    movie = models.ForeignKey(Movie, null=True, related_name='showtimes' )

Then you will access MovieShowtime like:

theater = MovieTheater.object.get(movie_theater='test')
for showtime in theater.showtimes.all:
  print "Movie: {} - Time: {}".format(showtime.movie.title, showtime.time)

Leave a comment