[查询和过滤]3. 如何在Django ORM中进行AND查询?

在这里插入图片描述
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。它将拥有领域usernamefirst_namelast_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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值