Reputation: 79
Can you please tell me the approach to implement a TTL on Django model record?
For Example:Remove all values stored over more than x minutes.
Upvotes: 1
Views: 1824
Reputation: 32294
The first thing you would need to do is to add a field to your model that tracks the time the record was created. Passing auto_now_add=True
to a DateTimeField
means that it will automatically be populated by the time the record was created
class Values(models.Model):
key = models.CharField(max_length=20)
value = models.TextField(blank='False',default='')
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.key
Then you need a function that will delete records that are older than a certain age, a classmethod seems appropriate
@classmethod
def delete_old_records(cls, minutes=5):
cut_off = datetime.datetime.now() - datetime.timedelta(minutes=minutes)
cls.objects.filter(created__lt=cut_off).delete()
Now you need to add a method for calling this function from a script, a custom management command is ideal
class Command(BaseCommand):
help = 'Deletes old Values'
def handle(self, *args, **options):
Values.delete_old_records()
Then you need to schedule this command, something like cron or celerybeat would be good for this
Upvotes: 1