Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading