Reputation: 39
I'm stuck with manytomany relations in Django.
Here are my models :
class Actors(models.Model):
name = models.CharField(verbose_name="Actor's name", max_length=128)
# other stuff
class Meta:
verbose_name = "Actor"
ordering = ["name"]
def __str__(self):
return self.name
class Movies(models.Model):
title = models.CharField(verbose_name="Movie's title", max_length=128)
casting = models.ManyToManyField("models.Actors", verbose_name="Actors")
# other stuff
class Meta:
verbose_name = "Movie"
ordering = ["title"]
def __str__(self):
return self.title
I'm looking to print all the movies played by one actor. So in my actor's views I got :
def actor(request, id):
actor = get_object_or_404(Actors, id=id)
# Trying to get the movies played by the actor
# -> goal : filter the casting field and compare
# the actors_id in movies_movies_actors to
# the id parameter
movies = Movies.casting.filter(actors_id=id)
return render(request, 'actors/actor.html.twig', {'actor': actor, 'movies': movies})
I don't find the right way to access the casting field and get all the rows where 'id' appears.
Can you help me ?
Thx
Upvotes: 0
Views: 53
Reputation: 8525
with related_name
it's more powerfull:
def actor(request, id):
actor = get_object_or_404(Actors, id=id)
movies = actor.movies_set.all()
return render(request, 'actors/actor.html.twig', {'actor': actor, 'movies': movies})
Upvotes: 2
Reputation: 5310
If my memory served me right the following syntax should be what you are looking for.
movies = Movies.objects.filter(casting__actors_id=id)
Upvotes: 0