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

Django ORM反向外键查询求助:按价格及价格变动次数排序

Django 商品价格模型问题解决方案

1. 获取关联价格的商品并按价格排序:代码优化建议

你的原代码存在逻辑和效率问题:

  • 直接用order_by("price__amount")会触发JOIN,导致同一个商品因多条Price记录重复出现在结果里,不符合“按商品当前价格排序”的需求
  • prefetch_related和这种JOIN排序冲突,反而会增加查询次数,降低效率

正确高效的实现方式

如果要按商品最新价格排序,同时保证每个商品只出现一次,推荐用子查询获取最新价格:

from django.db.models import Subquery, OuterRef

# 子查询:获取每个商品的最新价格
latest_price_subq = Price.objects.filter(
    product=OuterRef('pk')
).order_by('-timestamp').values('amount')[:1]

# 给商品标注最新价格,过滤无价格的商品,再排序
queryset = Product.objects.annotate(
    latest_price=Subquery(latest_price_subq)
).filter(latest_price__isnull=False).order_by('latest_price')

如果需要同时预取所有价格历史记录,结合Prefetch优化:

from django.db.models import Subquery, OuterRef
from django.db.models import Prefetch

latest_price_subq = Price.objects.filter(
    product=OuterRef('pk')
).order_by('-timestamp').values('amount')[:1]

queryset = Product.objects.annotate(
    latest_price=Subquery(latest_price_subq)
).filter(latest_price__isnull=False).order_by('latest_price').prefetch_related(
    Prefetch("price_set", queryset=Price.objects.order_by('-timestamp'))
)

这里给预取的Price记录按时间倒序排列,方便快速获取当前价格。


2. 按近10天价格变动次数排序的实现

基础版:统计近10天的Price记录数量(新增即算变动)

from django.db.models import Count, Q
from django.utils import timezone

ten_days_ago = timezone.now() - timezone.timedelta(days=10)

# 给商品标注近10天价格记录数,按数量倒序
queryset = Product.objects.annotate(
    price_change_count=Count(
        'price_set',
        filter=Q(price_set__timestamp__gte=ten_days_ago)
    )
).order_by('-price_change_count')

进阶版:仅统计价格实际变化的次数(排除同价格重复记录)

如果需要排除连续相同价格的情况,只统计价格真正变动的次数,用窗口函数对比相邻价格:

from django.db.models import Window, F, Count, Q
from django.db.models.functions import Lag
from django.utils import timezone

ten_days_ago = timezone.now() - timezone.timedelta(days=10)

# 筛选出近10天内价格发生变化的记录
changed_prices = Price.objects.filter(
    timestamp__gte=ten_days_ago
).annotate(
    # 获取上一条价格记录
    prev_price=Window(
        expression=Lag('amount'),
        partition_by='product',
        order_by=F('timestamp').asc()
    )
).filter(
    # 排除第一条记录(无前置价格),且当前价格和上一条不同
    prev_price__isnull=False, 
    prev_price__ne=F('amount')
)

# 统计每个商品的变动次数并排序
queryset = Product.objects.annotate(
    price_change_count=Count(
        'price_set',
        filter=Q(price_set__in=changed_prices)
    )
).order_by('-price_change_count')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 00:52:44