>>> for post in posts: ... print(post.title) ... second-post hi
新增
1 2 3 4 5 6
>>> post = Post(title='created from shell', slug='create-from-shell', body='this is body', author=user, status= 'draft') >>> post <Post: created from shell> >>> post.save() >>> posts <QuerySet [<Post: second-post>, <Post: hi>]>
這裡需要.save() 才會將資料儲存到資料庫裡
更新
1 2 3 4 5
>>> post.title 'created from shell' >>> post.title = 'new created from shell' >>> post <Post: new created from shell>
更新倒是蠻容易的,只要用個= 即可
first()
第一個對象
1 2 3
>>> post = Post.objects.all().first() >>> post <Post: created from shell>
last()
最後一個對象
1 2 3 4 5 6
>>> post = Post.objects.all().last() >>> post <Post: hi> >>> posts = Post.objects.all() >>> posts <QuerySet [<Post: created from shell>, <Post: hi>]>
order_by()
1 2 3 4 5 6
>>> post = Post.objects.order_by('title') >>> post <QuerySet [<Post: created from shell>, <Post: hi>, <Post: second-post>]> >>> post = Post.objects.order_by('-title') >>> post <QuerySet [<Post: second-post>, <Post: hi>, <Post: created from shell>]>
可以用-去調整正序或是倒序,這時返回的會是 QuerySet
也可以使用索引[0],來返回指定的值:
1 2 3
>>> post = Post.objects.filter(title='hi')[0] >>> post <Post: hi>
這時返回的就是單一值
delete()
1 2 3 4 5
>>> post = post.filter(title='second-post') >>> post.delete() (1, {'blog.Post': 1}) >>> Post.objects.all() <QuerySet [<Post: created from shell>, <Post: hi>]>
评论