How to fix RuntimeWarning: DateTimeField Question.date_time received a naive datetime?

I want to delete 60 seconds old records but I am getting this error

RuntimeWarning: DateTimeField Question.date_time received a naive datetime (2022-08-27 16:09:30.659947) while time zone support is active.

def delete(self,request):
    expiry_date_time = - timedelta(seconds=60)
    print('Expiry time = ',expiry_date_time)
    count = Question.objects.filter(date_time__gte = expiry_date_time).delete()
    resp = {'resp' : 'All questions deleted.','Total question deleted':len(count)}
    return Response(resp)

use [Django-doc] instead, this will add the timezone to the timestamp:

from django.http import JsonResponse
from django.utils.timezone import now

# …

def delete(self, request):
    expiry_date_time = now() - timedelta(seconds=60)
    count, __ = Question.objects.filter(date_time__gte=expiry_date_time).delete()
    return JsonResponse(
        {'resp': 'All questions deleted.', 'Total question deleted': count}
Back to Top