Django ORM 字段查询表达式(Field lookup expressions)

在 Django ORM(以及 Django Filter / QuerySet API)中,

针对字段的比较操作(>、<、>=、<=、= 等)

都是通过 "字段查询表达式(Field lookup expressions)" 来实现的。


🔤 一、Django ORM 比较运算符对照表

比较运算 含义 Django 查询关键字(lookup) 示例
= 等于 exact(或直接省略) price__exact=100price=100
> 大于 gt (greater than) price__gt=100
< 小于 lt (less than) price__lt=100
>= 大于等于 gte (greater than or equal) price__gte=100
<= 小于等于 lte (less than or equal) price__lte=100
!= 不等于 exclude(price__exact=100)~Q(price=100) 不直接支持 ne
区间 在范围内 range price__range=(50, 100)
模糊匹配 包含(不区分大小写) icontains name__icontains='pump'
模糊匹配 开头匹配(不区分大小写) istartswith name__istartswith='acid'
模糊匹配 结尾匹配(不区分大小写) iendswith name__iendswith='valve'
空值判断 为空 isnull=True date__isnull=True
不为空 非空 isnull=False date__isnull=False
集合判断 属于列表 in status__in=['new','done']

🧩 二、示例:在 ORM 查询中使用

python 复制代码
from warehouse.models import Item

# 大于
Item.objects.filter(price__gt=100)

# 小于等于
Item.objects.filter(stock__lte=500)

# 在范围内
Item.objects.filter(created_at__range=('2025-10-01', '2025-10-09'))

# 等于(完全匹配)
Item.objects.filter(name__exact='Pump-A')

# 模糊匹配
Item.objects.filter(name__icontains='pump')

# 不等于
Item.objects.exclude(price__exact=0)

🧠 三、在 django-filter 中使用这些运算符

你可以让前端用这些"比较字母"来动态传参:

python 复制代码
import django_filters
from .models import Item

class ItemFilter(django_filters.FilterSet):
    price = django_filters.NumberFilter(field_name='price', lookup_expr='exact')
    price_gt = django_filters.NumberFilter(field_name='price', lookup_expr='gt')
    price_lt = django_filters.NumberFilter(field_name='price', lookup_expr='lt')
    price_gte = django_filters.NumberFilter(field_name='price', lookup_expr='gte')
    price_lte = django_filters.NumberFilter(field_name='price', lookup_expr='lte')

    class Meta:
        model = Item
        fields = ['price']

📘 示例请求:

复制代码
/api/items/?price_gt=100&price_lte=500

🧱 四、简写记忆口诀:

运算符 Django 写法 英文含义
> gt greater than
< lt less than
>= gte greater than or equal
<= lte less than or equal
= exact exactly equal

相关推荐
IT 行者1 分钟前
SpringBoot版本升级插件:用OpenRewrite 轻松升级 Spring Boot 2 到 4
java·spring boot·后端
乾元9 分钟前
LLM 自动生成安全基线与等保合规初稿——把“网络工程事实”转译为“可审计的制度语言”
运维·网络·人工智能·python·安全·架构
全栈陈序员11 分钟前
【Python】基础语法入门(二十四)——文件与目录操作进阶:安全、高效地处理本地数据
开发语言·人工智能·python·学习
是有头发的程序猿14 分钟前
Python爬虫实战:面向对象编程构建高可维护的1688商品数据采集系统
开发语言·爬虫·python
摸鱼仙人~17 分钟前
企业级 RAG 问答系统开发上线流程分析
后端·python·rag·检索
serve the people23 分钟前
tensorflow tf.nn.softmax 核心解析
人工智能·python·tensorflow
癫狂的兔子31 分钟前
【BUG】【Python】eval()报错
python·bug
啃火龙果的兔子31 分钟前
java语言基础
java·开发语言·python
masterqwer31 分钟前
day42打卡
python
不会飞的鲨鱼34 分钟前
抖音验证码滑动轨迹原理(很难审核通过)
javascript·python