Home > Enterprise >  Django make the object create only once per 24 hours
Django make the object create only once per 24 hours

Time:09-13

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.

CodePudding user response:

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)
  • Related