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

  • Post author:
  • Post category:其他


在这里插入图片描述

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

等等。

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%)'



版权声明:本文为angelgods原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。