Django-如何在生效日期之前查询最近的不同行?

时间:2019-04-16 21:49:20

标签: django django-queryset

我有一个模型,其中包含有效的过时利率。这些费率上值得注意的字段是nametypeeffective_daterate

我需要能够过滤修改率,以仅获取特定类型且在特定日期之前的费率。

ModifierRate.objects.filter(
                type=settings.MODIFIER_RATE_TYPES_TAX,
                effective_date__lte=date)

该查询可能返回具有相同的nametype的费率,因此我需要在这两个字段上将它们区分。

.distinct('name', 'type')`

但是,如果名称和类型重复,则需要最新的名称。

.order_by('-effective_date')

毕竟,我需要对这些对象的费率求和。

.aggregate(rate__sum=Coalesce(Sum('rate'), 0))['rate_sum']

如果我尝试将所有这些东西粉碎在一起,我会得到

    raise NotImplementedError("aggregate() + distinct(fields) not implemented.")
NotImplementedError: aggregate() + distinct(fields) not implemented.

我已经搜索了一段时间,有很多类似的问题都使用values_listannotate,但我认为这不是我想要的。

如何获取某个日期之前在使用最新不同汇率的字段名称和类型上不同的汇率总和?

谢谢。

1 个答案:

答案 0 :(得分:0)

You could use django Subquery expressions, read the link for details.

most_recent = ModifierRate.objects.filter(
    name=OuterRef('name'), 
).order_by(
    '-effective_date'
)

result = ModifierRate.objects.filter(
    type=settings.MODIFIER_RATE_TYPES_TAX,
    effective_date__lte=date
    pk=Subquery(most_recent.values('pk')[:1])
).aggragate(
    rate__sum=Coalesce(Sum('rate'), 0)
)['rate_sum']
相关问题