0

I have a model full of effective dated rates. The notable fields on these rates are name, type, effective_date, and rate.

I need to be able to filter the modifier rates to get only rates of a certain type and before a certain date.

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

That query may return rates with the same name and type so I need them to be distinct on those two fields.

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

However, if there is a duplicate name and type I need the most recent one.

.order_by('-effective_date')

After all that I need to aggregate Sum the rates on those objects.

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

If I try and smash all these things together I get

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

I've been googling for awhile and there are many similar questions that make use of values_list and annotate but I don't think that's what I want.

How do I get the sum of the rates before a certain date that are distinct on fields name and type where the most recent distinct rate is used?

Thanks.

1 Answer 1

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']
2
  • I don't this would remove duplicates on type and name would it? And how do I make sure that the duplicates being removed are the older ones? Apr 16, 2019 at 22:45
  • Thanks, I'll give this a try and report back Apr 17, 2019 at 15:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.