[英]How to add a `or` condition filter in this prefetch_related query filter?
I have a qs
filter code like bellow: 我有一个像下面这样的
qs
过滤器代码:
qs2 = qs1.filter(ipv4s__ip=ip).prefetch_related(
Prefetch('ipv4s', queryset=IPv4Manage.objects.filter(ip=ip)))
now I want to add a OR
logic filter in this filter. 现在,我想在此过滤器中添加一个
OR
逻辑过滤器。
how to add a or
condition filter in this query filter? 如何在此查询过滤器中添加
or
条件过滤器?
I mean I want to add a or condition filter like this: it will meet this 我的意思是我想添加一个或条件过滤器,例如:它将满足
filter(ipv4s__ip=ip).prefetch_related(
Prefetch('ipv4s', queryset=IPv4Manage.objects.filter(ip=ip)))
condition or it will meet ip='1.1.1.1'
. 条件,否则它将满足
ip='1.1.1.1'
。
How to make this come true? 如何实现这一目标?
Use an IN
query; 使用
IN
查询; you basically are selecting on WHERE ip IN (<ip>, '1.1.1.1')
here: 您基本上是在这里选择
WHERE ip IN (<ip>, '1.1.1.1')
:
filter(ipv4s__ip__in=(ip, '1.1.1.1')).prefetch_related(
Prefetch('ipv4s', queryset=IPv4Manage.objects.filter(ip__in=(ip, '1.1.1.1'))))
I'm assuming that you want to filter both the questions and the related IPv4Manage
objects you are prefetching here, so both ipv4s__ip__in
and ip__in
filters are used in the above example. 我假设您要过滤问题和此处要预取的相关
IPv4Manage
对象,因此在上面的示例中同时使用了ipv4s__ip__in
和ip__in
过滤器。 If you only wanted to filter, say, the prefetch query set, adjust accordingly. 如果您只想过滤预取查询集,请相应地进行调整。
The queryset
parameter otherwise takes a standard QuerySet
instance, so you can use standard query constructing syntax with Q()
objects to build more complex filters. 否则,
queryset
参数采用标准的QuerySet
实例,因此您可以对Q()
对象使用标准的查询构造语法,以构建更复杂的过滤器。
For example, if your query could not easily be satisfied with a IN (...)
filter, then building on OR
query works by using Q()
filters combined with the |
例如,如果使用
IN (...)
过滤器无法轻松满足查询条件,则可以通过将Q()
过滤器与|
组合使用,在OR
查询上进行构建 binary OR operator: 二进制OR运算符:
filter(Q(ipv4s__ip=ip) | Q(ipv4s__ip='1.1.1.1')).prefetch_related(
Prefetch('ipv4s', queryset=IPv4Manage.objects.filter(
Q(ip=ip) | Q(ip='1.1.1.1')
)))
Last but not least, if you are filtering your questions on the ip
column of the ipv4s
relationship, then you don't need to further filter the pre-fetch on the same conditions ! 最后但并非最不重要的一点是,如果要在
ipv4s
关系的ip
列上过滤问题,则无需在相同条件下进一步过滤预提取 ! That'll already be limited to the same filter, so it should be enough to just use: 它将已经限于同一过滤器,因此仅使用它就足够了:
filter(ipv4s__ip__in=(ip, '1.1.1.1')).prefetch_related('ipv4s')
The .prefetch_related('ipv4s')
will prefetch the IPv4Manage
objects that are connected to the questions that the filter()
returned, so they have already been limited to the same ip
column values. .prefetch_related('ipv4s')
将预取与filter()
返回的问题相关的IPv4Manage
对象,因此它们已被限制为相同的ip
列值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.