$ python manage.py shell $ from blog.models import Post, Comment $ post = Post.objects.all()
來看一下目前 post 是什麼:
1 2
>>> post <QuerySet [<Post: Lorem Ipsum2>, <Post: Lorem Ipsum>, <Post: created from shell>, <Post: hi>]>
在最後一篇 post 新增評論
1 2 3 4 5 6 7 8 9 10 11
>>> from blog.models import Post, Comment >>> post = Post.objects.all() >>> post <QuerySet [<Post: Lorem Ipsum2>, <Post: Lorem Ipsum>, <Post: created from shell>, <Post: hi>]> >>> post = post.last() >>> post <Post: hi> >>> com = Comment(post=post, username='text', email='[email protected]', body='here is a comment from shell') >>> com.save() >>> com <Comment: Comment by text on hi>
也可以透過.filter(id=).first()找到想要新增的文章
先使用 for 循環印出所有文章的 id,在使用 filter 找指定的文章
1 2 3 4 5 6 7 8 9 10 11 12 13
>>> post = Post.objects.all() >>> for p in post: ... print(p.id) ... 7 6 5 3 >>> post = Post.objects.filter(id=5).first() >>> com = Comment(post=post,username='Amy',email='[email protected]',body='this is comment from Amy') >>> com.save() >>> com <Comment: Comment by Amy on created from shell>
也可以看到 DB 的 blog_comment Table 裡面有資料:
可以從 post 調出 comments
1 2 3 4 5 6 7
>>> post = Post.objects.filter(id=5).first() >>> post.comments.all() <QuerySet [<Comment: Comment by Amy on created from shell>]> >>> for c in post.comments.all(): ... print(c) ... Comment by Amy on created from shell
# List of active comments for this post comments = post.comments.filter(active=True) #過濾出所有active的comment new_comment = None if request.method == 'POST': #如果表單發送post請求 comment_form = CommentForm(data=request.POST) # 讀取form數據,產生comment_form對象 if comment_form.is_valid(): #驗證是否正確 new_comment = comment_form.save(commit=False) #新建一個new_comment對象 new_comment.post = post new_comment.save() else: comment_form = CommentForm() #如果不是post 是get,就做一個form的顯示
评论