我必须在不使用manytomany字段的情况下建立电影和演员之间的关系我必须在django中只使用外键到目前为止我已经写了这段代码

i have to make a relation between movie and actor without using manytomany field i have to use only foreign key in django i've write this code so far

models.py


    class Movielist(models.Model) :
        Title = models.CharField(max_length=1000)
        Description = models.TextField(blank=True)
        ReleaseDate = models.DateTimeField(verbose_name='Release Date', blank=True)
        # NoOfActors = models.IntegerField()
        Upvote = models.IntegerField(default=0)
        Downvote = models.IntegerField(default=0)
        
        def __str__(self):
            return self.Title

    class Actorlist(models.Model):
        Name = models.CharField(max_length=1000)
        DateofBirth = models.DateTimeField(verbose_name='Date of Birth',blank=True)
        # NoOfActors = models.IntegerField()
    
        def __str__(self):
            return self.Name

    class ActorInMovie(models.Model):
        Movie = models.ForeignKey(Movielist, default=1, on_delete=models.CASCADE, blank=True)
        Actor = models.ForeignKey(Actorlist, default=1, on_delete=models.CASCADE, blank=True)
        
        def __str__(self):
            return self.Movie.Title



views.py


    def Movie_Detail(request):
        MovieName = Movielist.objects.all()
        tablelist = ActorInMovie.objects.all()
        return render(request, 'Collection/index.html', {'MovieName':MovieName, 'tablelist':tablelist})



index.html
<table border="solid">
        <th>Name</th>
        <th>Release Date</th>
        <th>Actors</th>
        {% for data in MovieName %}
        <tr>
            <td>{{ data.Title }}</td>
            <td>{{ data.ReleaseDate }}</td>
            <td>
                <ul>
                    {% for name in tablelist %}
                    <li>{{ name.Actor.Name }}</li>
                    {% endfor %}
                </ul>
            </td>
        </tr>
        {% endfor %}
    </table>

**我已经把这个输出了,谁能告诉我如何只过滤我的电影 ID 的数据我希望有人来帮我解决这个问题 [这是我得到的输出,但我想要过滤演员的名字 movielist.id][1]

  [1]: https://i.stack.imgur.com/BlAuP.png**

您正在将 ActorInMovie 中的所有对象选择到 tablelist,而不仅仅是相关对象。您根本不需要 tablelist。相反:

        {% for data in MovieName %}
        <tr>
            <td>{{ data.Title }}</td>
            <td>{{ data.ReleaseDate }}</td>
            <td>
                <ul>
                    {% for movie_actor in data.ActorInMovie %}
                    <li>{{ movie_actor.Actor.Name }}</li>
                    {% endfor %}
                </ul>
            </td>
        </tr>
        {% endfor %}

您可能还需要在 ActorInMovie 模型中使用 related_name 来告诉 django 您将如何识别相关字段:

Movie = models.ForeignKey(Movielist, default=1, on_delete=models.CASCADE, blank=True, related_name='ActorInMovie)

因为你要打印每部电影的所有演员,所以使用 prefetch_related(Another ref) 来获得更好的性能是个好主意,但如果你没有大量数据则不需要.