我想删除年龄超过一天的模特中的视频。
models.py
from __future__ import unicode_literals
import urllib
from django.core.files import File
from django.db import models
from PIL import Image
from datetime import datetime
from django.utils import timezone
import os
class video(models.Model):
video_title = models.CharField(max_length=250)
video_link = models.CharField(max_length=250)
video_thumbnail = models.ImageField(upload_to = '',blank = True)
image_url = models.CharField(max_length=250,blank = True)
upload_date = models.DateTimeField(blank=True)
def cache(self):
if self.image_url and not self.video_thumbnail:
result = urllib.urlretrieve(self.image_url)
self.video_thumbnail.save(
os.path.basename(self.image_url),
File(open(result[0]))
)
self.save()
def __str__(self):
return self.video_title + "," + self.video_link + "," + str(self.upload_date)
在shell中,我会查询删除年龄超过一天的视频,如下所示:
video.objects.filter((datetime.datetime.now() - (upload_date)).total_hours > 24)
但是我收到以下错误:
In [6]: video.objects.filter((datetime.datetime.now() - (upload_date)).total_hours > 24)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-6-0c1ffc162513> in <module>()
----> 1 video.objects.filter((datetime.datetime.now() - (upload_date)).total_hours > 24)
NameError: name 'upload_date' is not defined
为什么我收到错误?
答案 0 :(得分:1)
此查询是向后的。您不能将datetime.datetime.now()
作为第一个参数传递;这是要比较的字段名称。您需要撤消查询,以便您要求所有在upload_date之前减去24小时的视频:
target_time = datetime.datetime.now() - datetime.timedelta(hours=24)
video.objects.filter(upload_date__lte=target_time)