限制Django表中的行数 [英] Limit the number of rows in a Django table

查看:121
本文介绍了限制Django表中的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型文件中有一个表,我希望对其进行设计,以使表中的行数限制为十。当超出限制时,最早的行将被删除。在某些情况下,这是为了在前端进行显示,向用户显示他们已访问的十个最新链接。我是Django新手,所以如果有人对如何执行此操作有任何建议,将不胜感激!

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!

推荐答案

编写一个自定义的 save 方法,该方法检查 YourObject.objects.all()的长度,然后删除最旧的方法当长度等于10时。

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.

类似于以下内容的行:

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

    super(YourModel, self).save(*args, **kwargs)

这篇关于限制Django表中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆