unique_for_date only works in the case of ModelForm. Also, If this field is listed in excluded, it will skip validation.
As per documentation
This is enforced by Model.validate_unique() during model validation
but not at the database level. If any unique_for_date constraint
involves fields that are not part of a ModelForm (for example, if one
of the fields is listed in exclude or has editable=False),
Model.validate_unique() will skip validation for that particular
constraint.
You need another field that will be unique by created_at like
class MyModel(models.Model):
# Add this field
my_field = models.CharField(unique_for_date='created_at')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
deleted_at = models.DateTimeField(null=True, blank=True)
As you are using DateTimeField for created_at, only the date portion of this field will be considered.
I'd suggest overriding the save method of your model
class MyModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
deleted_at = models.DateTimeField(null=True, blank=True)
def save(self, *args, **kwargs):
try:
date_from = datetime.datetime.now() - datetime.timedelta(days=1)
MyModel.objects.get(created_at__gte=date_from)
# raise some save error
except MyModel.DoesNotExist:
super(MyModel,self).save(*args,**kwargs)