'Created Field(DateTimeField) auto_now_add=True is not working in Abstract Class in Django
class TimeStampMixin(models.Model):
id = models.CharField(max_length=60,editable=False,primary_key=True,default=generate_unique_id)
created = models.DateTimeField(editable=False)
modified = models.DateTimeField(auto_now=True)
def save(self, *args, **kwargs):
if not self.id:
print("SAVING WHILE CREATE")
self.created = timezone.now()
print("MODIFY WHILE UPDATE")
self.modified = timezone.now()
return super().save(*args, **kwargs)
class Meta:
abstract = True
class Sport(TimeStampMixin):
name = models.CharField(max_length=100, unique=True)
image = models.ImageField(upload_to=path_and_rename,null=True,blank=True)
def __str__(self):
return self.name
def save(self, *args, **kwargs):
self.name = self.name.upper()
return super(Sport, self).save(*args, **kwargs)
Explaination
I have created an abstract model TimeStampMixin with custom save method.
Then i have inherited from TimeStampMixin model to Sport Model.
Now whenever i'm creating Sport object it raising django.db.utils.IntegrityError: null value in column "created" of relation "events_sport" violates not-null constraint DETAIL: Failing row contains (id, Test, image,2022-04-10 13:30:00+00, 2022-04-10 14:30:00+00, 2022-04-10 12:00:00+00).
Also Custom save method from timestampmixin not called. (Not print Anything).
Solution I need: While updating an object created field is also get updated. auto_now_add=True in datetimeField attribute is not working!!. How to prevent this?
Solution 1:[1]
I have reset the database and use this code
class TimeStampMixin(models.Model):
id = models.CharField(max_length=60,editable=False,primary_key=True,default=generate_unique_id)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
Than its working fine for me!
Solution 2:[2]
Try if self._state.adding: instead of if not self.id:.
Note: if you use auto_now, you can't set new value for this field. Following document "it’s not just a default value that you can override." https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.DateField.auto_now
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Saif |
| Solution 2 | Evgeni Shudzel |
