Search code examples
djangodjango-rest-frameworkdjango-orm

How to fix delete record after some date in django not working?


I am trying to delete records after expiry_date_time is less than or equal to current date time but it was not working properly.

Also giving this error

RuntimeWarning: DateTimeField Question.date_time received a naive datetime (2022-08-28 10:15:19) while time zone support is active.

API deleting wrong records.

def delete(self, request):
   
    count = 0
    count, _ = Question.objects.filter(
        expiry_date_time__lte=datetime.now(timezone.utc).today()
        .strftime('%Y-%m-%d %H:%M:%S')).delete()

    print(now().today()
          .strftime('%Y-%m-%d %H:%M:%S'))

    resp = {'Total question deleted': count}
    print(resp)
    return Response(resp)

Solution

  • Have you tried the query Question.objects.filter( expiry_date_time__lte=datetime.now(timezone.utc).today() .strftime('%Y-%m-%d %H:%M:%S')) itself and see whether it also returned an empty set? If it does you need to start with the queryset.

    Furthermore, if your expiry_date_time is already of type DateTimeField, you should not parse it to a string with strftime anymore, and maybe that the reason why it does not work :)