65π
auto_now
takes precedence (obviously, because it updates field each time, while auto_now_add
updates on creation only). Here is the code for DateField.pre_save
method:
def pre_save(self, model_instance, add):
if self.auto_now or (self.auto_now_add and add):
value = datetime.date.today()
setattr(model_instance, self.attname, value)
return value
else:
return super().pre_save(model_instance, add)
As you can see, if auto_now
is set or both auto_now_add
is set and the object is new, the field will receive current day.
The same for DateTimeField.pre_save
:
def pre_save(self, model_instance, add):
if self.auto_now or (self.auto_now_add and add):
value = timezone.now()
setattr(model_instance, self.attname, value)
return value
else:
return super().pre_save(model_instance, add)
10π
According to the django documentation using both auto_now
and auto_now_add
in your model fields as True
will result in an error because they are both mutually exclusive.
- [Django]-Comma separated lists in django templates
- [Django]-Django β "no module named django.core.management"
- [Django]-Django β How to rename a model field using South?
10π
These fields are built into Django for expressly this purpose β auto_now fields are updated to the current timestamp every time an object is saved and are therefore perfect for tracking when an object was last modified, while an auto_now_add field is saved as the current timestamp when a row is first added to the database and is therefore perfect for tracking when it was created.
- [Django]-Specifying a mySQL ENUM in a Django model
- [Django]-Find object in list that has attribute equal to some value (that meets any condition)
- [Django]-Django: How can I protect against concurrent modification of database entries
6π
As Official Django documentation says β
auto_now
, auto_now_add
and default
are mutually exclusive and will result in an error if used together
- [Django]-Django models avoid duplicates
- [Django]-Django query get last n records
- [Django]-Using a UUID as a primary key in Django models (generic relations impact)
1π
If a filed in a model contains both the auto_now and auto_now_add set to True will result in an error like this:
ERRORS:
appname.Model.field_name: (fields.Efield_number) The options auto_now, auto_now_add, and default are mutually exclusive. Only one of these options may be present.
- [Django]-Django REST framework serializer without a model
- [Django]-How do I filter query objects by date range in Django?
- [Django]-How to tell if a task has already been queued in django-celery?