[查询和过滤]2. 如何在Django ORM中进行OR查询

在这里插入图片描述

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等等。
A common requirement is performing OR filtering with two ore more conditions. Say you want find all users with firstname starting with ‘R’ and last_name starting with ‘D’.
一个常见的要求是在OR两个或者多个条件下执行过滤。假设您要查找所有以“R”开头的名字和“D”开头的last_name的所有用户。

Django provides two options.
Django提供了两个选项。

  • queryset_1 | queryset_2
  • filter(Q(<condition_1>)|Q(<condition_2>)

2.1. The query in detail

The 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%' OR last_name LIKE 'D%';

在这里插入图片描述
Similarly our ORM query would look like
同样,我们的ORM查询看起来像

queryset = User.objects.filter(
        first_name__startswith='R'
    ) | User.objects.filter(
    last_name__startswith='D'
)
queryset
<QuerySet [<User: Ricky>, <User: Ritesh>, <User: Radha>, <User: Raghu>, <User: rishab>]>

You can also look at the generated query.
您还可以查看生成的查询。

In [5]: str(queryset.query)
Out[5]: '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% OR "auth_user"."last_name"::text LIKE D%)'

Alternatively, you can use the Q objects.
或者,您可以使用Q

from django.db.models import Q
qs = User.objects.filter(Q(first_name__startswith='R')|Q(last_name__startswith='D'))
If you look at the generated query, the result is exactly the same
In [9]: str(qs.query)
Out[9]: '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% OR "auth_user"."last_name"::text LIKE D%)'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值