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

相关推荐
大鸡腿同学19 分钟前
黄仁勋点透的 AI 真相:能实现你知道但做不到的,却实现不了你不知道的
后端
FfHUCisI25 分钟前
Go 编译过程全景
开发语言·后端·golang
FfHUCisI26 分钟前
Golang 语法分析与 AST:Parser 与 go/ast
开发语言·后端·golang
临沂GEO1 小时前
GEO搜索优化科普|正规地理位置流量运营入门指南
大数据·人工智能·python·流量运营
大模型码小白2 小时前
Spring AI Tool 实现自然语言操作 MySQL 数据库详解
服务器·开发语言·数据库·人工智能·python·mysql·spring
++==2 小时前
RESTful详解:核心思想、框架、与HTTP的区别,API的设计风格
后端·http·restful
荷蒲3 小时前
【小白量化Qbuddy】利用AI学习中文Python
人工智能·python·学习
IT_陈寒3 小时前
Vue的响应式更新有时候真的不听话
前端·人工智能·后端
向生4 小时前
Ubuntu Caddy 保姆级完整教程
后端
数据狐(Datafox)4 小时前
京东商品列表API技术解析与落地应用(含标准 JSON 示例)
java·大数据·前端·人工智能·python·数据分析·json