[Answered ]-Django sum of time differences from model fields

1👍

In your view you write:

context['design_time'] = Portfolio.objects.all().annotate(design_time=...)

Here your choice of the key is not very descriptive (even you were tricked by this name of yours it seems). Here design_time is a QuerySet of Portfolio objects, hence there is no such thing as design_time.design_time. Instead if you loop over design_time you will get Portfolio instances which will have design_time annotated onto them. To be more descriptive first rename this key in the context to something like:

context['portfolios'] = Portfolio.objects.all().annotate(design_time=...)

Next in your template loop over this:

{% for portfolio in portfolios %}
    {{ portfolio.design_time }}
{% endfor %}

Also in your query you use the ExpressionWrapper on the Sum, instead you should use Sum on the ExpressionWrapper:

Portfolio.objects.all().annotate(
    design_time = Sum(
        ExpressionWrapper(
            F('projects__design_end') - F('projects__design_start'),
            output_field=DurationField()
        )
    )
)

Leave a comment