在Django 2中创建评论系统

时间:2019-07-05 18:26:38

标签: django django-models system

我尝试在Django 2中创建评论系统

我尝试将评论分配给帖子ID。我仍然似乎无法弄清楚。

我的模型。py:

class post_id(models.Model):
    user_post_id = models.IntegerField(null=True)

class Comments(models.Model):
    post = models.ForeignKey(post_id, on_delete=models.CASCADE, 
null=True)
    post_comment = models.TextField(null=True)
    comment_id = models.CharField(max_length=255, null=True)


class posts(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post_text = models.TextField()
    post_likes = models.IntegerField(null=True)
    post_id = models.ForeignKey(post_id, on_delete=models.CASCADE, 
 null=True)
    post_category = models.ForeignKey(Category, on_delete=models.CASCADE)
    post_likes = models.IntegerField(default=0, null=True)
    post_comments = models.ForeignKey(Comments, on_delete=models.CASCADE, 
null=True)

    datetime = models.DateTimeField(auto_now_add=True)
    user_ip = models.CharField(max_length=100)
    user_agent = models.CharField(max_length=255)

3 个答案:

答案 0 :(得分:0)

我不明白为什么你要把它分开

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
    post_comment = models.TextField(null=True)


class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post_text = models.TextField()
    post_category = models.ForeignKey(Category, on_delete=models.CASCADE)
    post_likes = models.IntegerField(default=0)  
    datetime = models.DateTimeField(auto_now_add=True)
    user_ip = models.CharField(max_length=100)
    user_agent = models.CharField(max_length=255)

我从邮政信息中删除了评论,因为如果需要,您可以致电:

comments = post.comments.all()

Django默认将id字段。您可以通过以下方式获得:comment.idpost.id

答案 1 :(得分:0)

这就是我实现它的方式,并且运行良好。

class Post(models.Model):
    post_text = models.CharField(max_length=1500)
    post_date = models.DateField(auto_now_add=True)
    post_time = models.TimeField(auto_now_add=True)
    user = models.ForeignKey(Profile,on_delete=models.CASCADE)


    def __str__(self):
        return self.post_text[:30]

class PostComment(models.Model):

    comment_text = models.TextField(max_length=1000, help_text="Enter comment about blog here.")
    author = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True)
# Foreign Key used because BlogComment can only have one author/User, but users can have multiple comments
    post_date = models.DateTimeField(auto_now_add=True)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    comment_likes = models.PositiveIntegerField(default=0)

    def __str__(self):
        return self.post.__str__()+'....  commented by '+self.author.__str__()

可以在这样的视图中使用

def get_queryset(self):
    return PostComment.objects.filter(post=self.kwargs['pk'])

网址

path('postcomments/<int:pk>',GetPostComment.as_view()),

答案 2 :(得分:0)

使用 Django-comments-xtd。它是一个很棒的模块,可以让您非常轻松地拥有一个非常漂亮的评论系统。它的python,无需从头开始!