加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 在django中自动删除超过10天的数据

发布时间:2020-12-16 22:40:56 所属栏目:Python 来源:网络整理
导读:在我的django项目中,我想自动删除超过10天的数据. 我怎么写这个观点?它如何自动执行? 在我的模型中有一个post_date字段,我想通过它检查它是否是10天. model.py: class CustomerLeads(models.Model):title = models.CharField(max_length=100,null=True,bl

在我的django项目中,我想自动删除超过10天的数据.

我怎么写这个观点?它如何自动执行?

在我的模型中有一个post_date字段,我想通过它检查它是否是10天.

model.py:

class CustomerLeads(models.Model):
title = models.CharField(max_length=100,null=True,blank=True)
budget = models.IntegerField(default=0,blank=True)
posting_date = models.CharField(max_length=300,blank=True)
quantity = models.IntegerField(default=1,blank=True)

我怎么能得到差异天.我从当前日期获得2016-12-15< type'datetime.date'>我的发布日期值是2016年12月12日< type'unicode'>

提前致谢.

最佳答案
执行此操作的好方法是在django Link中使用管理命令功能.

在python文件中编写代码并将其放在cron中以便在特定时间每天运行.在程序中查找超过10天的对象并删除它们用于您的用例.

之为dateiff不适合您的原因是因为您使用字符字段在代码中存储当前日期时间.将posting_date的字段类型更改为django datetime字段. Link

posting_date = models.DateTimeField(auto_now_add=True)

添加管理程序.这将是这样的:

# purge_old_data.py

from django.core.management.base import BaseCommand,CommandError
from cus_leads.models import CustomerLeads 
from datetime import datetime,timedelta

class Command(BaseCommand):
    help = 'Delete objects older than 10 days'

    def handle(self,*args,**options):
        CustomerLeads.objects.filter(posting_date__gte=datetime.now()-timedelta(days=10)).delete()
        self.stdout.write('Deleted objects older than 10 days')

如何运行此命令:

python 

我假设的项目结构:

cus_leads/
    __init__.py
    models.py
    management/
        __init__.py
        commands/
            __init__.py
            purge_old_data.py
    tests.py
    views.py


但是,我建议你不要删除对象.而是将字段添加为is_deleted,并在10天后将其设置为true.这将有助于您进行分析.

另外@ e4c5指出:

You should delete it or move to an archive table because boolean
columns cannot be indexed effectively and this is going to slow down
your DB over time.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读