0

I have a qs filter code like bellow:

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.

how to add a or condition filter in this query filter?

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'.

How to make this come true?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
qg_java_17137
  • 3,310
  • 10
  • 41
  • 84

1 Answers1

3

Use an IN query; you basically are selecting on WHERE ip IN (<ip>, '1.1.1.1') here:

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. 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.

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 | binary OR operator:

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! 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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343