具有评论/评论回复关系的自我引用ForeignKey

时间:2017-02-02 02:30:32

标签: python django django-models django-templates django-views

我试图回复我的评论,并且不确定自己的外键是如何工作的。这是我的Comment模型。

class Comment(models.Model):
    user = models.ForeignKey(User, blank=True, null=True)
    destination = models.CharField(default='1', max_length=12, blank=True)
    parent_id = models.IntegerField(default=0)
    reply = models.ForeignKey('self', blank=True, null=True)
    comment_text = models.TextField(max_length=350, blank=True, null=True)

    def __str__(self):
        return str(self.comment_text)

现在这是我的初始评论(父评论)视图的样子:

def user_comment(request):
    if request.is_ajax():
        comment = CommentForm(request.POST or None)
        ajax_comment = request.POST.get('text')
        id = request.POST.get('id')

        if comment.is_valid():
            comment = Comment.objects.create(comment_text=ajax_comment, destination=id, user=request.user)
            comment.save()
            username = str(request.user)
            return JsonResponse({'text': ajax_comment, 'username': username, 'id': comment.id})

这样就可以创建Comment的常规实例。现在我在尝试回复评论(单独观点):

def comment_reply(request):
    if request.is_ajax():
        comment = CommentForm(request.POST or None)
        reply_text = request.POST.get('reply_text')
        id = request.POST.get('id')
        parent_id = request.POST.get('parent_id')
        parent = Comment.objects.get(id=parent_id)

        if comment.is_valid():
            comment = Comment.objects.create(comment_text=reply_text, destination=id,
                                             user=request.user, parent_id=parent_id, reply=parent)
            comment.save()
            username = str(request.user)
            return JsonResponse({'reply_text': reply_text, 'username': username})

reply=parent是创建回复Comment对象的正确方法吗?我正在努力解决如何将两者联系起来的问题。我的模板,只是呈现父评论,如下所示:

    {% for i in comment_list %}
        <div class='comment_div' data-comment_id="{{ i.id }}">
            <div class="left_comment_div">
                <div class="username_and_votes">
                    <h3><a class='username_foreign'>{{ i.user }}</a></h3>
                </div>
                <br>
                <p>{{ i.comment_text }}</p>
            </div>
                <a class="reply">reply</a><a class="cancel_comment">cancel</a>
                <span><a class="comment_delete" data-comment_id="{{ i.id }}">x</a></span>
        </div>
    {% endfor %}

所以,一旦我连接了父评论和回复评论,它将如何在上面的模板中呈现?

1 个答案:

答案 0 :(得分:0)

删除reply字段只需添加父字段,如下所示。

parent = models.ForeignKey("self", blank=True, null=True, related_name="comment_parent")

添加评论:

if request.POST.get('parent_id'):
     parent = Comment.objects.get(id=request.POST.get('parent_id'))
     comment = Comment.objects.create(comment_text=reply_text, destination=id, user=request.user, parent=parent)