You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何简化冗余的Django ORM查询代码并兼顾可读性?

简化Django查询逻辑:兼顾功能与可读性

原冗余代码

has_videos = self.request.query_params.get('has_videos')
if has_videos:
    if has_videos == 'true':
        entries = User.objects.filter(videos__isnull=False)
    elif has_videos == 'false':
        entries = User.objects.filter(videos__isnull=True)
else:
    entries = User.objects.all()

可读性差的三元运算符写法

entries = Pet.objects.all() if has_photos not in ['true', 'false'] \
else Pet.objects.filter(photos__isnull=False) if has_photos == 'true' \
else Pet.objects.filter(photos__isnull=True)

优化方案

方案1:字典映射法(最简洁直观)

用字典直接关联参数值与对应的查询集,通过get方法快速获取结果,默认值设为全量查询:

has_videos = self.request.query_params.get('has_videos')

query_map = {
    'true': User.objects.filter(videos__isnull=False),
    'false': User.objects.filter(videos__isnull=True)
}

entries = query_map.get(has_videos, User.objects.all())

这种写法逻辑清晰,后续若要新增参数取值(比如'both'),直接在字典里添加对应项即可,维护成本低。

方案2:动态构建查询参数

如果需要更灵活地控制查询条件,可以先构建过滤参数字典,再执行查询:

has_videos = self.request.query_params.get('has_videos')

filter_args = {}
if has_videos == 'true':
    filter_args['videos__isnull'] = False
elif has_videos == 'false':
    filter_args['videos__isnull'] = True

entries = User.objects.filter(**filter_args) if filter_args else User.objects.all()

这种方式将条件构建与查询动作分离,适合后续可能添加多维度过滤的场景。

内容的提问来源于stack exchange,提问作者Anonymous Wizard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 19:26:15