将查询obj数据转换为datetime obj

时间:2017-02-23 19:21:15

标签: django

编写管理命令,删除超过两周的记录。 每个模型实例都有一个'confirmed_placed',我用它作为比较日期。 ('confirm_placed'是CharField,因为它是以预定格式动态生成的。)

如果我的项目模型如下:

class HotItem(models.Model):
    item_no = models.CharField(max_length=30, unique=True, blank=False, null=False)
    ad_date = models.CharField(max_length=20, unique=False, blank=True, null=True, default=None)
    create_date = models.DateField(default=date.today)
    item_name = models.CharField(max_length=210, blank=True, null=True)
    comments = models.TextField(max_length=2000, blank=True, null=True) 
    reply = models.TextField(max_length=2000, blank=True, null=True)
    confirmed_placed = models.CharField(max_length=200, blank=True, null=True, default=None)

    def __str__(self):
        return u'%s %s %s %s %s' % (self.create_date, self.item_no, self.item_name, self.confirmed_placed, self.comments)

我需要的是将我的对象confirmed_placed值转换为日期时间obj的正确方法,并与twoweeksago进行比较(如下定义。)类似于:

from .models import HotItem as Item

twoweeksago = datetime.datetime.now() - datetime.timedelta(weeks=2)


class Command(BaseCommand):
    help = 'Delete hotlist items placed more than two weeks ago'

    def handle(self, *args, **options):

        **hotrecords = Item.objects.filter(datetime.datetime.strptime(confirmed_placed.replace('.','').replace(',',''),' %b %d %Y')__gt=twoweeksago)**

        for record in hotrecords:
            record.delete()

        self.stdout.write(self.style.SUCCESS('Successfully deleted record old records'))

关于格式化查询的正确方法的任何想法?

0 个答案:

没有答案