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 表
| id | name |
|---|---|
| 1 | A |
| 2 | B |
| 3 | C |
CustomerOrder 表
| id | customer | item | datetime_of_purchase |
|---|---|---|---|
| 1 | A | item_3 | 2021-11-10 10:00:00 |
| 2 | A | item_2 | 2021-11-11 10:00:00 |
| 3 | B | item_1 | 2021-11-11 10:00:00 |
| 4 | A | item_1 | 2021-11-12 10:00:00 |
| 5 | B | item_2 | 2021-11-12 10:00:00 |
| 6 | C | item_1 | 2021-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
相关产品推荐
相关产品推荐

