我有一点代码如下。
for prop in Property.objects.all():
for platform_device in prop.platformdevice_set.all():
if platform_device.platform == cur_platform:
if platform_device.applicable_devices.filter(name=cur_device).exists():
if platform_device.applicable_events.filter(name=cur_event).exists():
print("Found my correct even and need to continue processing.")
else:
for group in platform_device.event_group.all():
if group.applicable_events.filter(name=cur_event).exists():
print("Found my correct even and need to continue processing.")
有点乱,但目前还能用。我被卡住的地方是这部分。
if platform_device.applicable_events.filter(name=cur_event).exists():
print("Found my correct even and need to continue processing.")
else:
for group in platform_device.event_group.all():
if group.applicable_events.filter(name=cur_event).exists():
print("Found my correct even and need to continue processing.")
基本上我所做的是检查 platform_device.applicable_events
来检查里面是否包含我的cur_event。如果包含,那么我需要从这个点开始继续处理。
否则,我需要从这个点继续处理。
我打算通过一个event_group(就是事件的分组),检查cur_event是否在其中一个组里面,然后继续处理。
我的问题是,如何才能使这两条途径最终都在同一个地方。我只是想防止在这两个位置有相同的代码。
我会尽量在数据库中做更多的工作。与其在python中 "过滤 "queryset,不如在db中过滤它。
for prop in Property.objects.filter(
platformdevice__platform=cur_platform,
platformdevice__applicable_devices=cur_device,
).filter(
Q(platformdevice__applicable_events=cur_event)
| Q(platform_device__event_group__applicable_events__name=cur_event)
):
#continue processing
的 foo__bar=baz
筛选关联表 foo
对于专栏 bar
有价值 baz
. 要过滤A或B值,你可以使用 Q表达式
Q(..) | Q(..)
Q(..) & Q(..)
(与普通过滤器相同)