Django的时间持续时间阈值仅允许数据插入
我在Django中有一个带有DateTimeField属性的模型。如果新数据的数据库和数据库中最新的DateTime字段之间的持续时间小于某些持续时间阈值,我想禁止在数据库中插入新数据。
class MyModel(models.Model):
time_stamp = models.DateTimeField(default=timezone.now, null=True)
当我今天想插入数据库时,并且我的数据库中的最新时间戳是昨天,而持续时间阈值是一个月(不可能使用此操作)。
I have a model in Django with a DateTimeField attribute. I want to forbid insertion of new data in the database if the duration between the datetime field of the new data and the latest datetime field in the database is less than some duration threshold.
class MyModel(models.Model):
time_stamp = models.DateTimeField(default=timezone.now, null=True)
When I want to insert a datapoint say today, and the latest time stamp in my database is yesterday, and the duration threshold is one month (this operation should not be possible).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在您的观点中定义此逻辑:
You can define this logic in your views like so:
如果确定以比在视图中放置保护逻辑更难的方式预防这种方法,则可以在视图中检查一下,您可以在模型的
保存
方法中检查。例如,django bulk_update以及RAW SQL仍然可以绕过此检查。某些数据库可能使您将支票放入数据库本身。
缺点是使用(例如)Django管理员可能会变得困难。在这种情况下,您可以通过首先重置时间戳来编程绕过支票。
If you are determined that this is prevented in a more hard manner than putting protection logic in view(s), then instead of checking in the view you can check in the model's
save
method.This check can still be bypassed, by Django bulk_update for example, and by raw SQL. Some databases may let you put the check into the database itself.
The downside is that fixing mistakes using (for example) the Django Admin may become difficult. In this case you can programmatically bypass the check by resetting the timestamp first.