WayBehind
WayBehind

Reputation: 1697

Django ORM Query - How to Subtract Time From Model Field?

I have query that returns Max time from my model field.

results = MyModel.objects.filter(
                id=pk,
                date__range=(start_time, end_time)
                ).values('my_id'
                ).annotate(max_time=Max('my_date_time'))

To this point, everything works great. Now I need to subtract time (60 min) from my my_date_time field.

The most convenient for me would be if I can somehow subtract the time directly in my html template. Any filters available for that?

If not, is there a way to use MySQL SUBTIME() function or Python timedelta with this query?

Suggestions and feedback is much appreciated!

If there already is a similar previously asked/answered question, somehow I missed it and I do apologize!

Edit:

Yes, the my_date_time field is a valid datetime model field.

Upvotes: 0

Views: 1142

Answers (1)

f43d65
f43d65

Reputation: 2302

from datetime import timedelta

results = MyModel.objects.filter(
                id=pk,
                date__range=(start_time, end_time)
                ).values('my_id'
                ).annotate(max_time=Max('my_date_time'))
for result in results:
    result['max_time'] -= timedelta(minutes=60)

Upvotes: 1

Related Questions