我在Django中遇到了许多关系。
以下是我的模特:
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
我正在打印一个演员播放的所有电影。 所以在演员的观点中我得到了:
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})
我找不到正确的方法来访问铸造字段并获取“id”出现的所有行。
你能帮助我吗?
THX
答案 0 :(得分:2)
related_name
它更强大:
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})
答案 1 :(得分:0)
如果我的记忆力正确,那么以下语法就应该是你想要的。
movies = Movies.objects.filter(casting__actors_id=id)