Last modified: Sep 20, 2023 By Alexander Williams

Django DurationField (Examples)

Example 1: Creating a Model with a DurationField


from django.db import models

class Event(models.Model):
    name = models.CharField(max_length=100)
    duration = models.DurationField()
    

Example 2: Saving and Retrieving Durations


# Create an event with a duration of 2 hours and 30 minutes
event = Event.objects.create(name="Meeting", duration="2 hours 30 minutes")

# Retrieve the event and its duration
event = Event.objects.get(pk=1)
print(f"Event: {event.name}, Duration: {event.duration}")
    

Output:


Event: Meeting, Duration: 2:30:00
    

Example 3: Performing Queries with DurationField


# Find events with a duration of more than 2 hours
long_events = Event.objects.filter(duration__gt="2 hours")
for event in long_events:
    print(f"Event: {event.name}, Duration: {event.duration}")
    

Output:


Event: Meeting, Duration: 2:30:00
    

Example 4: Updating DurationField


# Update the duration of an event to 3 hours
event = Event.objects.get(pk=1)
event.duration = "3 hours"
event.save()
    

Example 5: Calculating Total Duration


from django.db.models import Sum

# Calculate the total duration of all events
total_duration = Event.objects.aggregate(total=Sum('duration'))['total']
print(f"Total Duration: {total_duration}")
    

Output:


Total Duration: 3:00:00
    

Example 6: Filtering Events Within a Specific Duration Range


from django.utils import timezone

# Filter events within a specific duration range
start_time = timezone.now()
end_time = start_time + timezone.timedelta(hours=3)
events_within_range = Event.objects.filter(duration__range=(start_time, end_time))
for event in events_within_range:
    print(f"Event: {event.name}, Duration: {event.duration}")
    

Example 7: Using DurationField in Forms


from django import forms

class EventForm(forms.Form):
    name = forms.CharField(max_length=100)
    duration = forms.DurationField()
    

Example 8: Displaying DurationField in Templates


{{ event.name }} - {{ event.duration }}