You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中如何基于关联订单最新记录对客户进行反向过滤查询

模型定义
# 原模型定义(存在笔误,实际使用需修正)
class Customer(models.Model):
  name = models.CharField()

class CustomerOder(models.Model): # 笔误:应为 CustomerOrder
  customer = models.ForiengKey(Customer) # 笔误:应为 ForeignKey
  item = models.CharField()
  datetime_of_purchase = models.DateField() # 存储带时间的订单时间建议改为 DateTimeField
示例数据

Customer 表

idname
1A
2B
3C

CustomerOrder 表

idcustomeritemdatetime_of_purchase
1Aitem_32021-11-10 10:00:00
2Aitem_22021-11-11 10:00:00
3Bitem_12021-11-11 10:00:00
4Aitem_12021-11-12 10:00:00
5Bitem_22021-11-12 10:00:00
6Citem_12021-11-13 10:00:00
需求说明

筛选出最新购买的商品为item_1的客户,预期返回结果:

<QuerySet [<Customer: A>, <Customer: C>]>
实现方案

推荐使用Django ORM子查询方案,仅执行一次SQL查询,性能优异:

from django.db.models import OuterRef, Subquery

# 子查询:获取对应客户的最新订单的商品名称
latest_order_item = CustomerOrder.objects.filter(
    customer_id=OuterRef('id')
).order_by('-datetime_of_purchase').values('item')[:1]

# 注解+过滤得到目标客户
target_customers = Customer.objects.annotate(
    latest_purchase_item=Subquery(latest_order_item)
).filter(latest_purchase_item='item_1')

返回的target_customers就是符合要求的Customer查询集,和预期结果完全一致。


内容的提问来源于stack exchange,提问作者Akram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 01:06:08