Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit the number of rows in a Django table

I have a table in my models file and I want to design it such that there is a limit to ten rows in the table. When the limit is exceeded the oldest row will be deleted. For some context this is for a display on the front end that shows a user the ten most recent links they have accessed. I am new to Django so if anyone had a suggestion on how to do this, it would be greatly appreciated!

like image 518
Parag Srivastava Avatar asked Aug 08 '13 20:08

Parag Srivastava


1 Answers

You could write a custom save method that checks the length of YourObject.objects.all(), and then deletes the oldest one when that length is equal to 10.

Something along the line of:

def save(self, *args, **kwargs):
    if YourModel.objects.count() == 10:
        objects[0].delete()

    super(YourModel, self).save(*args, **kwargs)
like image 79
Daniel Rosenthal Avatar answered Nov 15 '22 06:11

Daniel Rosenthal