本文介绍了暂时禁用auto_now / auto_now_add的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的模型:

class FooBar(models.Model):
    createtime = models.DateTimeField(auto_now_add=True)
    lastupdatetime = models.DateTimeField(auto_now=True)

要覆盖某些模型实例的两个日期字段(在迁移数据时使用)。目前的解决方案如下所示:

I want to overwrite the two date fields for some model instances (used when migrating data). The current solution looks like this:

for field in new_entry._meta.local_fields:
    if field.name == "lastupdatetime":
        field.auto_now = False
    elif field.name == "createtime":
        field.auto_now_add = False

new_entry.createtime = date
new_entry.lastupdatetime = date
new_entry.save()

for field in new_entry._meta.local_fields:
    if field.name == "lastupdatetime":
        field.auto_now = True
    elif field.name == "createtime":
        field.auto_now_add = True

有更好的解决方案吗?

推荐答案

我最近在测试我的时候面临这种情况应用。我需要强制一个过期的时间戳。在我的情况下,我通过使用查询更新来做这个伎俩。像这样:

I've recently faced this situation while testing my application. I needed to "force" an expired timestamp. In my case I did the trick by using a queryset update. Like this:

# my model
class FooBar(models.Model):
    title = models.CharField(max_length=255)
    updated_at = models.DateTimeField(auto_now=True, auto_now_add=True)



# my tests
foo = FooBar.objects.get(pk=1)

# force a timestamp
lastweek = datetime.datetime.now() - datetime.timedelta(days=7)
FooBar.objects.filter(pk=foo.pk).update(updated_at=lastweek)

# do the testing.

这篇关于暂时禁用auto_now / auto_now_add的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 14:05