一个 Django DetailView 中的两个模型并按它们之间的关系进行过滤

Two models in one Django DetailView and filtering by relation betwen them

我有一个问题。在我的 DetailView 中,我想放置来自两个模型的数据。此外,我想过滤它们,在我的 scenario-detail 上只有与特定场景相关的评论,由 ForeignKey->Scenario 相关。

我的views.py:

class ScenarioDetailView(LoginRequiredMixin, DetailView):
    model = Scenario

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['comments'] = Comment.objects.all()
        return context

而在 scenario_detail.html 我有一个简单的 {{ comments }}

我想在 views.py 中过滤我的评论对象,例如:Comment.objects.get(commentScenario=Scenario.id) 但它根本不起作用。

我的models.py:

class Scenario(models.Model):
    scenarioTitle = models.CharField(max_length=256)
    scenarioArea = models.ForeignKey(ScenarioArea, on_delete=models.CASCADE)
    scenarioAuthor = models.ForeignKey(User, on_delete=models.CASCADE)
    scenarioDate = models.DateTimeField(default=timezone.now)
    scenarioDescription = models.TextField()

    def __str__(self):
        return self.scenarioTitle

    def get_absolute_url(self):
        return reverse('scenario-detail', kwargs={'pk': self.pk})

class Comment(models.Model):
    commentText = models.CharField(max_length=256)
    commentScenario = models.ForeignKey(Scenario, on_delete=models.CASCADE)
    commentAuthor = models.ForeignKey(User, on_delete=models.CASCADE)
    commentDate = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.commentText

urls.py

path('scenario/<int:pk>/', ScenarioDetailView.as_view(), name='scenario-detail'),

有人可以帮助我吗?

您不需要向您的模板发送任何额外上下文来显示相关评论;由于您已经对您的Scenario相关评论后向关系

因此您只需在模板中使用 Scenario.comment_set.all 即可访问它们。

举个例子:

{% for comment in object.comment_set.all %}
  {{ comment }}
{% endfor %}

试试这个

class ScenarioDetailView(LoginRequiredMixin, DetailView):
    model = Scenario

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['comments'] = Comment.objects.filter(commentScenario=self.object)
        return context