Skip to content

Instantly share code, notes, and snippets.

@filipeximenes
Last active February 9, 2017 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save filipeximenes/3721b46afe379fe1b7341409350f608e to your computer and use it in GitHub Desktop.
Save filipeximenes/3721b46afe379fe1b7341409350f608e to your computer and use it in GitHub Desktop.
from django.utils import timezone
from myapp.models import Event
class EventListView(generics.ListView):
def get_queryset(self):
now = timezone.now()
upcoming = Event.objects.filter(date__gte=now).order_by('date')
passed = Event.objects.filter(date__lt=now).order_by('-date')
return list(upcoming) + list(passed)
now = timezone.now()
(Event.objects.annotate(
relevance=models.Case(
models.When(date__gte=now, then=1),
models.When(date__lt=now, then=2),
output_field=models.IntegerField(),
))
.order_by('relevance'))
now = timezone.now()
(Event.objects.annotate(
relevance=models.Case(
models.When(date__gte=now, then=1),
models.When(date__lt=now, then=2),
output_field=models.IntegerField(),
)).annotate(
timediff=models.Case(
models.When(date__gte=now, then=F('date') - now),
models.When(date__lt=now, then=now - F('date')),
output_field=models.DurationField(),
))
.order_by('relevance', 'timediff'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment