Overwrite auto_now for unittest

后端 未结 3 347
北荒
北荒 2021-01-12 15:50

I\'ve defined some timestamps for events in the database as auto_now_add, as the information should be stored with it\'s timestamp the same time the event is st

3条回答
  •  醉梦人生
    2021-01-12 16:42

    Another way of handling this is to use a QuerySet update after the instance is created which may be more useful depending upon your use case.

    As an update call is performed at the SQL level it will skip validation, signals and and custom save functionality. It will require a secondary database call which can impact performance so it should be used with consideration.

    for event in EVENT_TYPES:
        time = datetime.datetime.now() - datetime.timedelta(days=1)
        for i in range(48):
            time = time.replace(hour=i / 2)
            instance = NewEvent(name=event, quantity=i).save()
            NewEvent.objects.filter(pk=instance.pk).update(timestamp=time)
    

提交回复
热议问题