2017-02-02 82 views
1

我試圖對我的評論執行回覆,但不確定自己的ForeignKey的工作情況如何。這是我的Comment模型。具有評論/評論回覆關係的自我引用ForeignKey

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 %} 

所以一旦我連接父評論和回覆評論,如何將它在上面的模板呈現?

+0

這或許會成爲有用嗎? http://stackoverflow.com/q/4725343/2750819 – kshikama

+1

而不是'parent_id = models.IntegerField(默認= 0)'它應該是'parent = models.ForeignKey(「self」,blank = True,null = True) '。 –

回答

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)