soySoy nuevo en django y quiero listar objetos de mi modelo Post junto con sus respectivos comentarios con vistas basadas en clases ListView, pero por cada post se muestran todos los comentarios de todos los post ya que no sé como hacer para que se filtren los comentarios por post con esta clase. Alguien¿Alguien podría ayudarme? no sé si deba cambiar la relacion entre el modelo Post y Comment, o modificar la vista, o simplemente cambiar la forma de presentar los objetos en mi plantilla...
Models.py
Models.py
"""Post model."""
user = models.ForeignKey(User, on_delete=models.CASCADE)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
photo = models.ImageField(upload_to="posts/photos")
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
def __str__(self):
"""Return title and username"""
return "{} by @{}".format(self.title, self.user.username)
class Comment(models.Model):
"""Comment model."""
user = models.ForeignKey(User, on_delete=models.CASCADE)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True)
comment = models.TextField(blank=True)
def __str__(self):
"""Return user and pk"""
return "{} by @{}".format(self.pk, self.user.username)```
# Views.py
```class PostsFeedView(LoginRequiredMixin, ListView):
"""Return all published posts."""
template_name = "posts/feed.html"
model = Post
ordering = ("-created")
paginate_by = 30
context_object_name = "posts"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comments'] = Comment.objects.all()
context['form_comments'] = CommentForm()
return context```
# parte de la plantilla
```{% for comment in comments %}
<div class="media mb-2">
{% if comment.user.profile.picture %}
<img class="d-flex mr-2 rounded-circle" width="50px" height="50px" src="/media/{{ comment.user.profile.picture }}" alt="">
{% else %}
<img class="d-flex mr-2 rounded-circle" src="http://placehold.it/50x50" alt="">
{% endif %}
<div class="media-body">
<h5 class="mt-0">{{comment.user.username}}</h5>
{{comment.comment}}
</div>
</div>
{% endfor %}
</div>```
class Post(models.Model):
"""Post model."""
user = models.ForeignKey(User, on_delete=models.CASCADE)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
photo = models.ImageField(upload_to="posts/photos")
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
def __str__(self):
"""Return title and username"""
return "{} by @{}".format(self.title, self.user.username)
class Comment(models.Model):
"""Comment model."""
user = models.ForeignKey(User, on_delete=models.CASCADE)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True)
comment = models.TextField(blank=True)
def __str__(self):
"""Return user and pk"""
return "{} by @{}".format(self.pk, self.user.username)
Views.py
class PostsFeedView(LoginRequiredMixin, ListView):
"""Return all published posts."""
template_name = "posts/feed.html"
model = Post
ordering = ("-created")
paginate_by = 30
context_object_name = "posts"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comments'] = Comment.objects.all()
context['form_comments'] = CommentForm()
return context```
# parte de la plantilla
```{% for comment in comments %}
<div class="media mb-2">
{% if comment.user.profile.picture %}
<img class="d-flex mr-2 rounded-circle" width="50px" height="50px" src="/media/{{ comment.user.profile.picture }}" alt="">
{% else %}
<img class="d-flex mr-2 rounded-circle" src="http://placehold.it/50x50" alt="">
{% endif %}
<div class="media-body">
<h5 class="mt-0">{{comment.user.username}}</h5>
{{comment.comment}}
</div>
</div>
{% endfor %}
</div>