JacksWastedLife
JacksWastedLife

Reputation: 294

Django querySet order by date closest to today

I have a simple view that returns event dates and then is presented within a table on my page.

I need to order the data by the date closest to the current date only for dates in the future, not for dates that have passed.

This is my view

def dashboard_view(request):
    now = datetime.datetime.now().date
    game_list=Game.objects.all()
    event_list = Event.objects.all().order_by('event_date')
    
    return render(request,"dashboard.html",{"game_list":game_list, "event_list": event_list})

I was thinking of using datetime.datetime.now() but I can't figure out the logic/syntax to do this.

Thanks

Upvotes: 1

Views: 1004

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

You can filter the Events with Event.objects.filter(event_date__gte=today) to retrieve only Events that start today or in the future:

from django.utils.timezone import now

def dashboard_view(request):
    today = now().date()
    game_list=Game.objects.all()
    event_list = Event.objects.filter(event_date__gte=today).order_by('event_date')
    
    return render(request, 'dashboard.html', {'game_list':game_list, 'event_list': event_list})

Upvotes: 1

Related Questions