1

I have a model whose fields are datetimefields start_time and end_time I want to display on the API- start_time, end_time and the difference between them However, I don't want to use for or while loop to achieve this because it is too slow How can I get the difference on the API without looping

3
  • I don't get why looping is too slow. Django will loop as well since it retrieves the data from the database, and will do looping to "pack" the data in model objects. Commented May 12, 2020 at 18:00
  • Have you tried something like this, ModelKlass.objects.annotate(diff=F('field_1')-F('field_2')) ? Commented May 12, 2020 at 18:01
  • @ArakkalAbu: the problem is that this is that Django's "type system" does not reason this to be a DurationField. Commented May 12, 2020 at 18:06

1 Answer 1

1

You can annotate the queryset with the difference, and then use an ExpressionWrapper to convert this to a DurationField, and thus obtain a timedelta objects:

from django.db.models import DurationField, ExpressionWrapper, F

MyModel.objects.annotate(
    time_diff=ExpressionWrapper(
        F('end_time')-F('start_time'),
        output_field=DurationField()
    )
)

The MyModels that arise from this queryset will thus have an extra attribute time_diff that is a timedelta field containing the difference between end_time, and start_time.

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

Comments

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.