Django的时间持续时间阈值仅允许数据插入

发布于 2025-02-05 17:33:41 字数 284 浏览 1 评论 0原文

我在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

慕烟庭风 2025-02-12 17:33:43

您可以在您的观点中定义此逻辑:

from django.shortcuts import get_object_or_404
import datetime

def CreateNew(request, id):
    obj = get_object_or_404(MyModel, id = id) #Get the object from your database
    form = YourForm(request.POST or None, instance = obj) #create form instance to be rendered inside template

    diff = (timezone.now() - obj.time_stamp).total_seconds()
    threshold = datetime.timedelta(days=30).total_seconds()

    if diff < threshold: # Compare dates to check condition
        return HttpResponse('<h1>Not Allowed</h1>')
    elif form.is_valid(): # If condition is passed save form as you normally would
        form.instance.time_stamp = timezone.now() # Update time_stamp to current time
        form.save()
        return HttpResponseRedirect("/")

context = {
    'form': form
}
return render(request, "Your_template", context)

You can define this logic in your views like so:

from django.shortcuts import get_object_or_404
import datetime

def CreateNew(request, id):
    obj = get_object_or_404(MyModel, id = id) #Get the object from your database
    form = YourForm(request.POST or None, instance = obj) #create form instance to be rendered inside template

    diff = (timezone.now() - obj.time_stamp).total_seconds()
    threshold = datetime.timedelta(days=30).total_seconds()

    if diff < threshold: # Compare dates to check condition
        return HttpResponse('<h1>Not Allowed</h1>')
    elif form.is_valid(): # If condition is passed save form as you normally would
        form.instance.time_stamp = timezone.now() # Update time_stamp to current time
        form.save()
        return HttpResponseRedirect("/")

context = {
    'form': form
}
return render(request, "Your_template", context)
最偏执的依靠 2025-02-12 17:33:43

如果确定以比在视图中放置保护逻辑更难的方式预防这种方法,则可以在视图中检查一下,您可以在模型的保存方法中检查。

def save( self, *args, **kwargs):

    diff = (timezone.now() - self.time_stamp).total_seconds()
    threshold = datetime.timedelta(days=30).total_seconds()

    if diff < threshold: # Compare dates to check condition

        # not certain ValueError is the best choice of exception
        raise ValueError( 
            f"Can't save because {diff} seconds since the previous save, the minimum is {theshold}"
        )
    super().save( *args, **kwargs)

例如,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.

def save( self, *args, **kwargs):

    diff = (timezone.now() - self.time_stamp).total_seconds()
    threshold = datetime.timedelta(days=30).total_seconds()

    if diff < threshold: # Compare dates to check condition

        # not certain ValueError is the best choice of exception
        raise ValueError( 
            f"Can't save because {diff} seconds since the previous save, the minimum is {theshold}"
        )
    super().save( *args, **kwargs)

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文