Django模型验证日期和日期时间范围 [英] Django model validate date and datetime ranges

查看:434
本文介绍了Django模型验证日期和日期时间范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django模型中验证日期和dateTime间隔的最佳解决方案是什么?

What is the best solution to validate a date and dateTime interval in a Django model?

这是我的模型:

class PriceOption(Model):
    from_datetime = DateTimeField(verbose_name=_('from datetime'))
    to_datetime = DateTimeField(verbose_name=_('to datetime'))

    from_time = TimeField(verbose_name=_('from time'))
    to_time = TimeField(verbose_name=_('to time'))

我需要确保from_datetime发生在to_datetime之前,并且from_time和to_time也是如此。

And I need to make sure that from_datetime happens before to_datetime and the same for from_time and to_time.

我应该重写save方法吗?还是以某种方式验证器?

Should I override the save method? Or validators somehow?

我看到Postgres有Date和DateTime范围字段。这只会解决第一对字段。

I see that Postgres have Date and DateTime range fields. This would only solve the first pair of fields.

推荐答案

最好使用表单来验证时间范围,因为表单已经内置函数 clean()来满足您的需求:

It's better to use a form to validate the time range, form has already built in function clean() to fit your needs:

class PriceOptionForm(forms.ModelForm):
    # some normal ModelForm setup goes here
    def clean(self):
        cleaned_data = super(PriceOptionForm, self).clean()
        from_time = cleaned_data.get("from_time")
        end_time = cleaned_data.get("end_time")

        if from_time and end_time:
            if end_time < from_time:
                raise forms.ValidationError("End time cannot be earlier than start time!")
        return cleaned_data

这篇关于Django模型验证日期和日期时间范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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