【问题标题】:How to optimize queryset filtering如何优化查询集过滤
【发布时间】:2020-09-15 20:34:24
【问题描述】:

我有一点代码如下:

    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 django django-views django-queryset


    【解决方案1】:

    我会尝试在数据库中做尽可能多的工作。与其在 python 中“过滤”查询集,不如在 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 为列 bar 过滤相关表 foo,值为 baz。要过滤值 A 或 B,您可以使用 Q-expressions

    • 或:Q(..) | Q(..)
    • 和:Q(..) & Q(..)(与普通过滤器相同)

    【讨论】:

    • 我试图看这个并没有完全理解它。我试图将其粘贴到我的代码中进行实验,但出现“位置参数跟随关键字参数”错误。
    猜你喜欢
    • 2014-12-10
    • 2015-09-17
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多