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

相关推荐
C嘎嘎嵌入式开发4 小时前
(1)100天python从入门到拿捏
开发语言·python
qq_5470261794 小时前
SpringBoot+Redis实现电商秒杀方案
spring boot·redis·后端
过往入尘土4 小时前
服务端与客户端的简单链接
人工智能·python·算法·pycharm·大模型
软件开发技术深度爱好者4 小时前
用python制作相册浏览小工具
开发语言·python
沐曦可期4 小时前
标准编码与算法
javascript·python
我的xiaodoujiao4 小时前
从 0 到 1 搭建 Python 语言 Web UI自动化测试学习系列 8--基础知识 4--常用函数 2
前端·python·测试工具·ui
Rhys..4 小时前
Cucumber自学导航
javascript·python·bdd·cucumber
Code blocks4 小时前
SpringBoot自定义请求前缀
java·spring boot·后端
爱学大树锯4 小时前
【Spring Boot JAR 解压修改配置后重新打包全流程(避坑指南)】
spring boot·后端·jar