如何过滤列表是否包含参数?
在我的Django-Rest-Framework项目中,我列出了physical_server:
[
{
"id": 23,
"name": 'A1'
"ipv4s": [
{
"id": 313,
"ip": "43.243.33.33",
"netmask": "255.255.255.248",
"prefix": 29,
"is_gateway": false,
"is_network_ip": false,
"is_broadcast_ip": false,
"desc": null,
"ctime": "2018-04-26T21:17:34.868492+08:00",
"uptime": "2018-05-21T12:09:25.674283+08:00",
....
这是我的列表API视图:
class PhysicalServerListAPIView(ListAPIView):
serializer_class = PhysicalServerListSerializer
permission_classes = [AllowAny]
pagination_class = CommonPagination
def get_queryset(self):
query_params = self.request.query_params
ip_address = ''
try:
ip_address = query_params.pop('ip_address') # this maybe `43.243.33.33`
except Exception as e:
pass
qs = PhysicalServer.objects.filter(xxxx) # there I want the ip_address filtered if it in the `ipv4s`.
return qs
如何实现此过滤器?因为它不是物理服务器的属性。我无法使用filter(name='xxx')
来做到这一点。
修改-1
我知道我可以使用for循环来迭代查询集的ipv4s,但我不确定这是方便还是有效。
答案 0 :(得分:1)
要按相关型号过滤服务器,请使用__
(docs)符号:
ip_address = query_params.pop('ip_address')
qs = PhysicalServer.objects.filter(ipv4s__ip=ip_address)
要使服务器ipv4s
列表仅包含已过滤的ip使用prefetch_related
:
from django.db.models import Prefetch
qs = PhysicalServer.objects.filter(ipv4s__ip=ip_address).prefetch_related(Prefetch('ipv4s', queryset=IPV4S.objects.filter(ip=ip_address))
现在,服务器ipv4s
将仅显示已过滤的IP地址。
答案 1 :(得分:0)
abount过滤器如何:
def get_queryset(self):
query_params = self.request.query_params
ip_address = ''
try:
ip_address = query_params.pop('ip_address')
except Exception as e:
pass
qs = PhysicalServer.objects.all()
if ip_address:
qs = [p for p in qs if ip_address in [d['ip'] for d in p['ipv4s']]]
return qs