[英]Using Django ORM, Iterate through table records, test them and delete the record if needed
How would you iterate through a table, using the Django ORM, and test the datetime fields to see if they are 8 days old, then delete them if they True. 您将如何使用Django ORM遍历表,并测试datetime字段以查看它们是否存在8天,如果它们为True,则将其删除。
# models.py
from django.db import models
class Tweet(models.Model):
tweet_id = models.Charfield()
tweet_date = models.DatetimeField()
# tasks.py
from celery import shared_task
from datetime import datetime, timedelta
@shared_task(name='cleanup')
def cleanup():
tweets = MyModel.objects.all()
for tweet.tweet_date in tweets:
if tweets.tweet_date <= datetime.now() - timedelta(days=8):
# remove this record from the table
You can directly query the database for more than 8 days old tweets
using lte
and delete the resultant tweets
. 您可以使用
lte
直接在数据库中查询8天以上的旧tweets
并删除生成的tweets
。 There is no need of iterating over the results and then individually deleting all of them. 无需遍历结果,然后逐个删除所有结果。
@shared_task(name='cleanup')
def cleanup():
# filter and delete more than 8 days old tweets
Tweet.objects.filter(tweet_date__lte=datetime.now()-timedelta(days=8)).delete()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.