from django.db.models import Q from django.utils import timezone def filter_for_when(queryset, when=None): """ Return a filtered queryset which is valid for the given date Logic: Look for entries that have a starting date before when and either - No ending date - Ending date after "when" Returns a queryset, you'll neet to apply .first() or similar on it """ if not when: when = timezone.now() return queryset.filter(starting_date__lte=when).filter(Q(ending_date__gte=when) | Q(ending_date__isnull=True))