How to use Modal Foreign key

comment in a situation where my modal looks like this i want to display comments without having to go to different page

class Posts(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post_name = models.CharField(max_length=150)
    desription = models.CharField(max_length=200)
    image = models.ImageField(upload_to="images/uploads")
    like = models.ManyToManyField(User, related_name="liked", blank=True, default=None)
    like_count = models.BigIntegerField(default=0)
    date_added = models.DateField(auto_now_add=True, blank=True)

    # @property
    # def like_count(self):
    #     return self.like.count()

    def __str__(self):
        return self.desription

    class Meta:
        db_table = "Posts"
        ordering = ["date_added"]


class Comments(models.Model):
    post = models.ForeignKey(Posts, on_delete=models.CASCADE)
    comment = models.CharField(max_length=500)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date_added = models.DateField(auto_now=True, blank=True)

    class Meta:
        db_table = "Comments"
        ordering = ['date_added']

and in the index use

{{post.comment}} ???

Use ForeignKey.related_name

The name to use for the relation from the related object back to this one.

Example

class Comments(models.Model):
    post = models.ForeignKey(Posts, related_name="comments", on_delete=models.CASCADE)
    comment = models.CharField(max_length=500)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date_added = models.DateField(auto_now=True, blank=True)

    class Meta:
        db_table = "Comments"
        ordering = ['date_added']

now you can access comments of that perticular post like this

{{post.comments}} 
Back to Top