Home > Net >  Django querySet order by date closest to today
Django querySet order by date closest to today

Time:11-13

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

CodePudding user response:

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})
  • Related