创建对象
代码语言:javascript复制$ 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对象
创建
更新对象
代码语言:javascript复制>>> post.title = 'New title'
>>> post.save()
更新对象
获取对象
代码语言:javascript复制>>> all_posts = Post.objects.all()
>>> Post.objects.all()
<QuerySet [<Post: New title>, <Post: zx>]>
使用filter()方法
代码语言:javascript复制>>> 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>]>
包含字段查找方法的查询操作可以采用两个下划线予以构建
使用exclude()方法
排除特定的结果
代码语言:javascript复制>>> Post.objects.filter(publish__year=2019)
.exclude(title__startswith='zx')
使用order_by()
代码语言:javascript复制>>> Post.objects.order_by('title')
<QuerySet [<Post: New title>, <Post: zx>]>
>>> Post.objects.order_by('-title')
<QuerySet [<Post: zx>, <Post: New title>]>
默认升序,通过负号前缀降序排序
删除对象
代码语言:javascript复制>>> post = Post.objects.get(id=1)
>>> post.delete()
(1, {'blog.Post': 1})
创建模型管理器
代码语言:javascript复制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()
...
使用
代码语言:javascript复制>>> Post.published.filter(title__startswith='zx')
<QuerySet []>