Django 2 by Example
上QQ阅读APP看书,第一时间看更新

Using the filter() method

To filter a QuerySet, you can use the filter() method of the manager. For example, we can retrieve all posts published in the year 2017 using the following QuerySet:

Post.objects.filter(publish__year=2017)

You can also filter by multiple fields. For example, we can retrieve all posts published in 2017 by the author with the username admin:

Post.objects.filter(publish__year=2017, author__username='admin')

This equates to building the same QuerySet chaining multiple filters:

Post.objects.filter(publish__year=2017) \
.filter(author__username='admin')

Queries with field lookup methods are built using two underscores, for example, publish__year, but the same notation is also used for accessing fields of related models, such as author__username.