from django.db import models
class Post(models.Model):
post_title = models.CharField(max_length=120, default=None)
post_text = models.TextField()
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.post_title
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
sub_comment = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True)
author = models.CharField(max_length=50)
comment_text = models.CharField(max_length=250)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.author
Hello, i've got a question. How to preform displaying comment as a thread if i have models like this?
A comment can have multiple subcomments, so this model won't work. Replace sub_comment
with parent = models.ForeignKey(..., related_name='subcomments')
. Then you will be able to say comment.subcomments
which will give you a related object manager, so comment.subcomments.all()
will be a query of all subcomments that you can iterate over.