在没有 RuntimeWarning 的情况下删除 django 数据:DateTimeField 收到一个天真的日期时间
Delete django data without RuntimeWarning: DateTimeField received a naive datetime
我正在尝试删除 python django 数据库中 3 年前的数据。这是代码:
from datetime import datetime
from dateutil.relativedelta import relativedelta
def db_cleanup():
cleanup_start = datetime.utcnow().date()
three_years_ago = cleanup_start - relativedelta(years=3)
MyData.objects.filter(create_date__lt=three_years_ago).delete()
但是我收到了 RuntimeWarning:DateTimeField 收到了一个天真的日期时间。如何正确操作?
使用timezone.now()
创建一个感知日期时间然后将时间重置为午夜但保留一个日期时间对象(不是日期):
from django.utils import timezone
from dateutil.relativedelta import relativedelta
def db_cleanup():
cleanup_start = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
three_years_ago = cleanup_start - relativedelta(years=3)
MyData.objects.filter(create_date__lt=three_years_ago).delete()
我正在尝试删除 python django 数据库中 3 年前的数据。这是代码:
from datetime import datetime
from dateutil.relativedelta import relativedelta
def db_cleanup():
cleanup_start = datetime.utcnow().date()
three_years_ago = cleanup_start - relativedelta(years=3)
MyData.objects.filter(create_date__lt=three_years_ago).delete()
但是我收到了 RuntimeWarning:DateTimeField 收到了一个天真的日期时间。如何正确操作?
使用timezone.now()
创建一个感知日期时间然后将时间重置为午夜但保留一个日期时间对象(不是日期):
from django.utils import timezone
from dateutil.relativedelta import relativedelta
def db_cleanup():
cleanup_start = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
three_years_ago = cleanup_start - relativedelta(years=3)
MyData.objects.filter(create_date__lt=three_years_ago).delete()