Django - Models.DateTimeField - changing the dynamic value of auto_now_add

I have a Django model with DateTimeField where auto_now_add is set to True. It works well.

class Problem(models.Model): ... date_created = models.DateTimeField('created on', auto_now_add=True) 

I would like to bypass this parameter when creating test data or loading historical data (auto_now_add is set to False) to set the date as I want and go back to the standard behavior (auto_now_add is set to True).

Is there a way to dynamically change the class (by changing the class attribute?). This parameter does not affect the database and is likely to be triggered during the save phase.

I do not want: -)

 date_created = models.DateTimeField('created on', default=timezone.now) 

Thank you in advance

+1
django django-models
Oct 05 '16 at 20:45
source share
2 answers

I had a similar problem when importing data from another application using the import data script executed from a shell command. Since it is dynamically impossible to disable the auto_now_add or auto_now function, I had to use a modified settings module.

First we define the IMPORT variable in the source settings module:

 IMPORT = False 

and created a new module import_settings containing only:

 from my_app.settings import * IMPORT = True 

Then, defining my models, I added the code

 from django.conf import settings if settings.IMPORT: AUTO_NOW = False else: AUTO_NOW = True 

and used the value AUTO_NOW when setting DateTimeField

 created = models.DateTimeField(editable=False, null=True, blank=True, auto_now_add=AUTO_NOW) modified = models.DateTimeField(editable=False, null=True, blank=True, auto_now=AUTO_NOW) 

Finally, I started importing the script data using the -settings option of the control command:

 python manage.py shell --settings=my_app.import_settings 
0
Jan 02 '17 at 12:23
source share

Well, I spent that day learning and the first problem is how to get the model object and where in the code. I am in restricework mode in serializer.py, for example, in the __init__ serializer, it did not have a model yet. Now in to_internal_value you can get the model class, after receiving the field and after changing the properties of the field, as 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 
0
Aug 29 '17 at 19:14
source share



All Articles