$ python manage.py shell
>>> from django.contrib.auth.models import User
>>> from blog.models import Post
>>> user = User.objects.get(username='admin')
>>> post = Post(title='Another post',
... slug='anotjer-post',
... body='Post bodu.',
... author=user)
>>> post.save()
user = User.objects.get(username='admin') 通过用户名admin获取到user对象
创建
>>> post.title = 'New title'
>>> post.save()
更新对象
>>> all_posts = Post.objects.all()
>>> Post.objects.all()
<QuerySet [<Post: New title>, <Post: zx>]>
>>> Post.objects.filter(publish__year=2019)
<QuerySet [<Post: New title>, <Post: zx>]>
>>> Post.objects.filter(publish__year=2019,author__username='admin')
<QuerySet [<Post: New title>, <Post: zx>]>
>>> Post.objects.filter(publish__year=2019) \
.filter(author__username='admin')
<QuerySet [<Post: New title>, <Post: zx>]>
包含字段查找方法的查询操作可以采用两个下划线予以构建
排除特定的结果
>>> Post.objects.filter(publish__year=2019) \
.exclude(title__startswith='zx')
>>> Post.objects.order_by('title')
<QuerySet [<Post: New title>, <Post: zx>]>
>>> Post.objects.order_by('-title')
<QuerySet [<Post: zx>, <Post: New title>]>
默认升序,通过负号前缀降序排序
>>> post = Post.objects.get(id=1)
>>> post.delete()
(1, {'blog.Post': 1})
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager, self) \
.get_queryset() \
.filter(status='published')
class Post(models.Model):
object = models.Manager()
published = PublishedManager()
...
>>> Post.published.filter(title__startswith='zx')
<QuerySet []>