lukos06
lukos06

Reputation: 312

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

I have a question. In my DetailView I want to placed data from two models. Moreover, I want to filter them, that on my scenario-detail was only that comments related to specyfic scenario, related by ForeignKey->Scenario.

My 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

And in scenario_detail.html i have a simple {{ comments }}

I thinking on filtering my comment object in views.py, something like: Comment.objects.get(commentScenario=Scenario.id) but it didn't work at all.

My 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

And urls.py:

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

Could someone help me?

Upvotes: 0

Views: 750

Answers (2)

harmain
harmain

Reputation: 188

try this

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

Upvotes: 1

Pedram
Pedram

Reputation: 3920

You don't need to send any extra context to your template in order to show the related comments; As you already have the related comments to your Scenario with backward relationship.

So you can simply use Scenario.comment_set.all in your template to access them.

As an example:

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

Upvotes: 5

Related Questions