Here is my Django 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)
How can I make the object created only once per 24 hours? I know it's possible to do with unique_for_date
but cannot understand how https://docs.djangoproject.com/en/4.1/ref/models/fields/#unique-for-date
Also, I want to show an error if the user wanted to create more than once per 24 hours.
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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.