Me gustaría enumerar los comentarios en mi página de detalles de la publicación y quería ver cómo puedo conectar una vista a los comentarios específicos de una publicación determinada.
Modelos.py
class Post(models.Model): owner = models.ForeignKey( Profile, null=True, blank=True, on_delete=models.SET_NULL) title = models.CharField(max_length=200) body = models.TextField() Post_image = models.ImageField( null=True, blank=True, default='default.jpeg') create_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post', kwargs={'pk': self.pk}) class Meta: ordering = ['-create_date'] class Comment(models.Model): owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) post = models.ForeignKey(Post, on_delete=models.CASCADE) text = models.TextField() create_date = models.DateTimeField(auto_now_add=True)Vistas.py
class PostDetailView(DetailView): model = Post def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comment_list'] = Post.comment_set.all() return contextPuede acceder al objeto de detalle de DetailView con self.object :
class PostDetailView(DetailView): model = Post def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comment_list'] = self.object.comment_set .order_by('create_date') return context