'Sum of Duration Fields in Django

I am having a small issue in summing up two simple duration fields. I have two variables which contains two different duration fields. Basically, I just need to sum them in order to get the total time. The problem is that, the way the database is built, I can't use Sum or F or ExpressionWrapper because I have to accept also None values and, the calculation gives me a None value in return. I post some code:

views. py

duration_dual = Mission.objects.filter(
    training_course_id=1, solo_flight=False)
total_dual_duration = duration_dual.aggregate(eet=Sum(ExpressionWrapper(
    F('duration_dual'), output_field=IntegerField()), output_field=DurationField()))['eet']
if total_dual_duration != None:
    total_dual_duration = duration(total_dual_duration)

duration_solo = Mission.objects.filter(
        training_course_id=1, solo_flight=True)
    total_solo_duration = duration_solo.aggregate(eet=Sum(ExpressionWrapper(
        F('duration_solo'), output_field=IntegerField()), output_field=DurationField()))['eet']
    if total_solo_duration != None:
        total_solo_duration = duration(total_solo_duration)

models.py

class Mission(models.Model):
name = models.CharField(max_length=200)
duration_dual = models.DurationField(blank=True, null=True)
duration_solo = models.DurationField(blank=True, null=True)
training_course = models.ForeignKey(
    TrainingCourse, on_delete=models.CASCADE)
note = models.TextField(null=True, blank=True)
solo_flight = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

In fact, what I need to do is just adding the total_solo_duration and total_dual_duration variables. I tried with datetime or timedelta but I can't figure out the proper way to do so. Thank you very much in advance



Solution 1:[1]

In the end I solved in a pretty easy way. I converted in datetime object my variables and add them to a zero time object.

    solo_dur = dt.strptime(total_solo_duration, '%H:%M')
    dual_dur = dt.strptime(total_dual_duration, '%H:%M')
    time_zero = dt.strptime('00:00', '%H:%M')
    total_duration = solo_dur - time_zero + dual_dur

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Giorgio Scarso