Limit the number of rows in a Django table

I have a table in my models file, and I want to create it so that the table has a limit of up to ten rows. When the limit is exceeded, the oldest row will be deleted. For some context, this is for display on the front panel, which shows the user the last ten links that they accessed. I am new to Django, so if anyone had a suggestion on how to do this, we would be very grateful!

+4
source share
2 answers

You can write your own save method, which checks the length of YourObject.objects.all() , and then removes the oldest one when that length is 10.

Something along the line:

 def save(self): objects=YourObject.objects.all() if objects.count() == 10: objects[0].delete() self.save() 
+2
source

In my opinion, you can use Signals . A post_save in this case. Thus, you save the logic of creating and deleting an object separately.

Since you want the oldest be deleted, I assume that you have a created field in the model.

Once you save ,

 def my_handler(sender, instance, **kwargs): qs = MyModel.objects.order_by('created') #ensure ordering. if qs.count() > 10: qs[0].delete() #remove the oldest element class MyModel(models.Model): title = models.CharField('title', max_length=200) created = models.DateTimeField(auto_add_now=True, editable=False) post_save.connect(my_handler, sender=MyModel) 

Of course, nothing prevents you from using the pre_save signal, but use it only if you are absolutely sure that the save method will not work.

+3
source

Source: https://habr.com/ru/post/1496036/


All Articles