Reputation: 339
Here is my model :
class Movie(models.Model):
genre = models.ManyToManyField(Genre)
class Genre(models.Model):
genre_eng = models.CharField(max_length=200)
def __str__(self):
return "{}".format(self.genre_eng)
and here is my view method :
def info(request, id):
movie_info = Movie.objects.get(id=id)
return render(request,'info.html', {'movie_info': movie_info})
I can already print the name of the movie like this in info.html
file:
genre : {{movie_info.title}}
How Can I access the genre_eng
in the info.html
file?
each movie may have multiple genres.
Upvotes: 1
Views: 740
Reputation: 88519
If you want to access all the Genre associated with Movie instance,
use movie_info.genre.all()
. If you want to access genre_eng
use .values_list()
def info(request, id):
movie_info = Movie.objects.get(id=id)
genre_eng_queryset = movie_info.genre.all()
genre_eng_values = movie_info.genre.values_list('genre_eng', flat=True)
return render(request, 'info.html',
{'movie_info': movie_info, 'genre_eng_queryset': genre_eng_queryset, 'genre_eng_values': genre_eng_values})
Upvotes: 2