0

I have this table:

id  supply   event_date   value_average
----------------------------------------
1     a      01-01-2018        5
2     b      02-01-2018        6
3     a      02-01-2018        7
4     b      03-01-2018        8
5     c      03-01-2018        9

I am trying to get the latest value for each supply based on event_date column. I can get the latest event, but I did not found a way to return the value_average as well.

values_average = Purchase.objects \
    .values('supply') \
    .annotate(last=Max('event_date')) \
    .order_by()

current return:

a        02-01-2018
b        03-01-2018
c        03-01-2018

expected return:

a        02-01-2018      7
b        03-01-2018      8
c        03-01-2018      9

2 Answers 2

1

I found a way to do that by following this answer:

Django: select values with max timestamps or join to the same table

values_average = Purchase.objects \
            .filter(farm=farm, supply__in=queryset) \
            .order_by('supply', '-event_date') \
            .distinct('supply')

It will only work with Postgres. The final result will be a normal queryset with the latest events. Just take care if your model has Meta ordering.

Django docs on this: https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.distinct

Sign up to request clarification or add additional context in comments.

Comments

0

I think you just have to add the value_average attribute to the values you want to return :

values_average= Purchase.objects.values('supply','value_average').annotate(last=Max('event_date'))

3 Comments

If I add value_average the result query will group by value_average too, and give me the wrong result. with value_average: ...GROUP BY "event_event"."supply_id", "event_event"."value_average" without value_average: ...GROUP BY "event_event"."supply_id"
Im not sure I get you but did you try to group by supply ? like this : values_average= Purchase.objects.values('supply','value_average').annotate(last=Max('event_date')).groupby('suply')
As far as I know, .groupby() does not exists in the ORM. To group by something we must use values(). docs.djangoproject.com/en/2.1/topics/db/aggregation/#values Please, If I am missing something, could you point me out the docs related to it?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.