Temporarily disable auto_now / auto_now_add

后端 未结 12 1215
刺人心
刺人心 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:36

    copy of Django - Models.DateTimeField - Changing dynamically auto_now_add value

    Well , I spent this afternoon find out and the first problem is how fetch model object and where in code . I'm in restframework in serializer.py , for example in __init__ of serializer it could not have the Model yet . Now in to_internal_value you can get the model class , after get the Field and after modify the field properties like in this example :

    class ProblemSerializer(serializers.ModelSerializer):
    
        def to_internal_value(self, data): 
            ModelClass = self.Meta.model
            dfil = ModelClass._meta.get_field('date_update')
            dfil.auto_now = False
            dfil.editable = True
    

提交回复
热议问题