You can .annotate(…)
[Django-doc] each Timesheet
object with:
from django.db.models import DurationField, ExpressionWrapper, F, IntegerField
Timesheet.objects.annotate(
total_time=ExpressionWrapper(
ExpressionWrapper(F('out') - F('entry'), output_field=IntegerField()) -
ExpressionWrapper(F('lunch_end') - F('lunch'), output_field=IntegerField()),
output_field=DurationField()
)
)
Here each Timesheet
object that arises from this queryset will have an extra attribute .total_time
which will contain the duration the person worked (so minus the luch break).
Or you can sum all records up with an .aggregate(…)
[Django-doc]:
from django.db.models import DurationField, ExpressionWrapper, F, IntegerField
Timesheet.objects.aggregate(
total_time=Sum(
ExpressionWrapper(F('out') - F('entry'), output_field=IntegerField()) -
ExpressionWrapper(F('lunch_end') - F('lunch'), output_field=IntegerField()),
output_field=DurationField()
)
)['total_time']
if the lunch
and lunch_end
can be None
/NULL
, you can work with Coalesce
[Django-doc]:
from django.db.models import DurationField, ExpressionWrapper, F, IntegerField, Value
from django.db.models.functions import Coalesce
Timesheet.objects.aggregate(
total_time=Sum(
ExpressionWrapper(F('out') - F('entry'), output_field=IntegerField()) -
Coalesce(ExpressionWrapper(F('lunch_end') - F('lunch'), output_field=IntegerField()), Value(0)),
output_field=DurationField()
)
)['total_time']
If you thus have .annotate(…)
d all Timesheet
records, and passed these as c
, you can use:
{% for ci in c %}
{{ ci.data }}: {{ ci.entry }} - {{ ci.out }}; {{ ci.total_time }}
{% endfor %}
CLICK HERE to find out more related problems solutions.