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

相关推荐
都叫我大帅哥6 小时前
Docker Swarm 部署方案
后端
Irene.ll6 小时前
DAY23
python
都叫我大帅哥6 小时前
在Swarm中部署Nacos并配置外部MySQL
后端
专注于大数据技术栈6 小时前
java学习--Collection的迭代器
java·python·学习
想摆烂的不会研究的研究生13 小时前
每日八股——Redis(1)
数据库·经验分享·redis·后端·缓存
毕设源码-郭学长13 小时前
【开题答辩全过程】以 基于SpringBoot技术的美妆销售系统为例,包含答辩的问题和答案
java·spring boot·后端
梨落秋霜13 小时前
Python入门篇【文件处理】
android·java·python
Java 码农14 小时前
RabbitMQ集群部署方案及配置指南03
java·python·rabbitmq
追逐时光者14 小时前
精选 10 款 .NET 开源免费、功能强大的 Windows 效率软件
后端·.net
追逐时光者14 小时前
一款开源、免费的 WPF 自定义控件集
后端·.net