If you are using django.contrib.auth, you will have a table called auth_user. It will have fields as username, first_name, last_name and more.
如果您正在使用django.contrib.auth,将有一个名为auth_user。它将拥有领域username,first_name,last_name等待
You would frequently need to want to perform AND operation, to find querysets which match multiple criteria.
您经常需要执行AND操作,以查找与多个条件匹配的查询集。
Say you want to find users with firstname starting with ‘R’ AND last_name starting with ‘D’.
假设您要查找以“R”开头的first_name和以“D”开头的last_name用户。
Django provides three options.
Django提供了三个选项。
- filter(<condition_1>, <condition_2>)
- queryset_1 & queryset_2
- filter(Q(<condition_1>) & Q(<condition_2>))
3.1. The query in detail详细查询
Our SQL query for the above condition will look something like
我们针对上述条件的SQL查询看起来像
SELECT username, first_name, last_name, email FROM auth_user WHERE first_name LIKE 'R%' AND last_name LIKE 'D%';
The default way to combine multiple conditions in filter is AND, so you can just do.
filter过滤中组合多个条件的默认方式是AND,因此您可以这样做。
queryset_1 = User.objects.filter(
first_name__startswith='R',
last_name__startswith='D'
)
Alternatively, you can explicitly use the & operator on querysets.
或者,您可以在查询集上显式使用&运算符。
queryset_2 = User.objects.filter(
first_name__startswith='R'
) & User.objects.filter(
last_name__startswith='D'
)
For complete customisability, you can use the Q objects.
为了实现完全可定制性,可以使用这些Q
queryset_3 = User.objects.filter(
Q(first_name__startswith='R') &
Q(last_name__startswith='D')
)
queryset_1
<QuerySet [<User: Ricky>, <User: Ritesh>, <User: rishab>]>
You can look at the generated query and verify that they are all same.
您可以查看生成的查询,并验证他们是否相同。
In [10]: str(queryset_2.query)
Out[10]: 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE ("auth_user"."first_name"::text LIKE R% AND "auth_user"."last_name"::text LIKE D%)'
In [11]: str(queryset_1.query) == str(queryset_2.query) == str(queryset_3.query)
Out[11]: True