Temporarily disable auto_now / auto_now_add

后端 未结 12 1216
刺人心
刺人心 2020-12-12 17:49

I have a model like this:

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


        
12条回答
  •  甜味超标
    2020-12-12 18:16

    For those looking at this when they are writing tests, there is a python library called freezegun which allows you to fake the time - so when the auto_now_add code runs, it gets the time you actually want. So:

    from datetime import datetime, timedelta
    from freezegun import freeze_time
    
    with freeze_time('2016-10-10'):
        new_entry = FooBar.objects.create(...)
    with freeze_time('2016-10-17'):
        # use new_entry as you wish, as though it was created 7 days ago
    

    It can also be used as a decorator - see the link above for basic docs.

提交回复
热议问题