测试游记

用 Django 写一个博客 · 第 03 篇|创建、更新和筛选文章对象

创建对象

$ 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>]>

使用filter()方法

虚构图书列表经过筛选,只留下带青色圆标记的记录
筛选返回满足条件的记录。图中只保留圆标记对应的图书,不改动原来的数据。
>>> 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()方法

排除特定的结果

>>> Post.objects.filter(publish__year=2019) \
        .exclude(title__startswith='zx')

使用order_by()

>>> 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 []>

本文视频讲解

打开或下载 MP4 ↗

查看系列目录 ↗

评论与讨论

使用 GitHub 账号留言,评论公开显示。

搜索文章