简体   繁体   English

如何在此prefetch_related查询过滤器中添加`或`条件过滤器?

[英]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__inip__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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM