Home > Back-end >  How to fix delete record after some date in django not working?
How to fix delete record after some date in django not working?

Time:08-29

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)

CodePudding user response:

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 :)

CodePudding user response:

If you have the expiry date as a DateTimeField, why are you formatting it in the strftime method, you can simply filter based on the datetime.now set it to the timezone you want.

Question.objects.filter(expiry_date_time__lte=datetime.now(tz=timezone.utc))

That should give your desired query, thereafter you can process as per the your business logic.

  • Related