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.