Temporarily disable auto_now / auto_now_add

后端 未结 12 1198
刺人心
刺人心 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条回答
  •  萌比男神i
    2020-12-12 18:15

    I'm late to the party, but similar to several of the other answers, this is a solution I used during a database migration. The difference from the other answers is that this disables all auto_now fields for the model under the assumption that there's really no reason to have more than one such field.

    def disable_auto_now_fields(*models):
        """Turns off the auto_now and auto_now_add attributes on a Model's fields,
        so that an instance of the Model can be saved with a custom value.
        """
        for model in models:
            for field in model._meta.local_fields:
                if hasattr(field, 'auto_now'):
                    field.auto_now = False
                if hasattr(field, 'auto_now_add'):
                    field.auto_now_add = False
    

    Then to use it, you can simply do:

    disable_auto_now_fields(Document, Event, ...)
    

    And it will go through and nuke all of your auto_now and auto_now_add fields for all of the model classes you pass in.

提交回复
热议问题