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

相关推荐
chushiyunen41 分钟前
python rest请求、requests
开发语言·python
cTz6FE7gA41 分钟前
Python异步编程:从协程到Asyncio的底层揭秘
python
铁东博客1 小时前
Go实现周易大衍筮法三变取爻
开发语言·后端·golang
baidu_huihui1 小时前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip
南 阳1 小时前
Python从入门到精通day63
开发语言·python
lbb 小魔仙1 小时前
Python_RAG知识库问答系统实战指南
开发语言·python
oak隔壁找我1 小时前
SpringBoot中MyBatis的Mapper的原理
后端
FreakStudio1 小时前
MicroPython LVGL基础知识和概念:底层渲染与性能优化
python·单片机·嵌入式·电子diy
oak隔壁找我2 小时前
Spring Boot 自动配置(Auto-configuration)的核心原理
后端