Search code examples
djangomany-to-many

Django : query a many to many relation


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


Solution

  • 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})