How to compare two dates (not time) in django-python project?

Viewed 304

Here It is my function to print the previous(oldTickets) and upcoming(newTickets) bookings.
journeyDate is database attribute(column name) which is of type date and ticketDetail is model name.
Here It is showing error in comparing date attributes.

def booking(request):
    if request.user.is_authenticated:
        user_name = request.user.username
        today = date.today()
        oldTickets = ticketDetail.objects.all()
        oldTickets = ticketDetail.objects.filter(userName=user_name).filter(ticketDetail.journeyDate<today)
        newTickets = ticketDetail.objects.all()
        newTickets = ticketDetail.objects.filter(userName=user_name).filter(ticketDetail.journeyDate>today)
        context = {'oldticket':oldTickets, 'newticket':newticket}
        return render(request, 'bookticket/myBookings.html', context)
    else:
        return redirect('/login')

Can anyone guide me, how to solve this error?
Thank You :)

1 Answers

You can work with the __lt [Django-doc] and __gt lookup [Django-doc] to specify filters with less than and greater than:

def booking(request):
    if request.user.is_authenticated:
        user_name = request.user.username
        today = date.today()
        oldTickets = ticketDetail.objects.filter(
            userName=user_name,
            journeyDate__lt=today
        )
        newTickets = ticketDetail.objects.filter(
            userName=user_name,
            journeyDate__gt=today
        )
        context = {'oldticket':oldTickets, 'newticket':newticket}
        return render(request, 'bookticket/myBookings.html', context)
    else:
        return redirect('/login')
Related