[Django]-How to fetch last 24 hours records from database

10👍

You can do it as below, where you add another argument in the filter call (assuming the rest of your function was working):

import datetime

def userorders(request):
    time_24_hours_ago = datetime.datetime.now() - datetime.timedelta(days=1)
    orders = Orders.objects.using('db1').filter(
        order_owner=request.user,
        order_started__gte=time_24_hours_ago
        ).extra(select={'order_ended_is_null': 'order_ended IS NULL',},)

Note that Orders is not a good choice for a variable name, since it refers to another class in the project and begins with caps (generally used for classes), so I’ve used orders instead (different case).

Leave a comment