博客五部曲之一 - 简单博客


1225 浏览 5 years, 3 months

16 QuerySet基础

版权声明: 转载请注明出处 http://www.codingsoho.com/

QuerySet为查询数据库的一些数据集合。

我们用python manage.py shell工具来熟悉这个概念,跟文件一样,我们也要在一开始import相关的对象。

>>> from posts.models import Post
>>> Post.objects.all()
<QuerySet [<Post: title>]>
>>> Post.objects.create(title="New Posts", content="new content")
<Post: New Posts>
>>> Post.objects.create(title="New Posts", content="new content")
<Post: New Posts>
>>> Post.objects.all()
<QuerySet [<Post: title>, <Post: New Posts>, <Post: New Posts>]>
>>> Post.objects.filter(title__icontains="New Posts")
<QuerySet [<Post: New Posts>, <Post: New Posts>]>
>>> queryset = Post.objects.all()
>>> for object in queryset:
...     print object.title
...     print object.id
...
title
1
New Posts
2
New Posts
3
>>>

Post.objects.all()和Post.objects.filter返回的都是QuerySet,可以轮询QuerySet访问对象。这些操作我们同样可以在view里进行操作。

def post_list(request):
    queryset = Post.objects.all()
    context = {
        'object_list': queryset,
        'title': 'List',
    }

    return render(request, "index.html",context)   

修改模板来显示这些对象列表,打印方式复制shell里的操作

    {% for object in object_list %}
        {{object.title}}<br>
        {{object.id}}
    {% endfor %}

页面显示会跟shell里显示的一致。