python – 用于验证日期范围的openERP函数
作者:互联网
我的模块中有两个字段,(start_date和end_date).我想验证日期范围,因为end_date必须大于start_date并显示错误消息,如“结束日期应该大于开始日期”这是mu cord.
from openerp.osv import osv, fields
class op_batch(osv.Model):
_name = 'op.batch'
_columns = {
'name': fields.char(size=25, string='Name', required=True),
'code': fields.char(size=15, string='Code', required=True),
'start_date': fields.date(size=15, string='Start Date', required=True),
'end_date': fields.date(size=15, string='End Date', required=True, onchange="validate_date_range"),
'state': fields.selection(
[('planned', 'Planned'), ('running', 'Running'), ('cancel', 'Cancel'), ('finished', 'finished')],
string='State'),
'course_id': fields.many2one('op.course', string='Course', ondelete='restrict', required=True),
}
def validate_date_range(self, cr, uid, vals, context=None):
en_date = date.start_date.value
st_date = date.end_date.value
if en_date < st_date:
raise Warning(_("End Date Should be greater than Start Date"))
return True
_sql_constraints = [('code', 'UNIQUE (code)', 'The CODE of the Batch must be unique!')]
_defaults = {
'state': 'planned',
}
我应该怎么做?请帮我这样做……
解决方法:
为了实现数据完整性,odoo支持两种类型的约束:SQL和Python.
SQL约束被添加到数据库中的表定义中,并由PostgreSQL实现.它们是使用类属性_sql_constraints定义的.它是具有约束标识符名称,约束的SQL和要使用的错误消息的元组列表.
Python约束
在v7 api中,
_constraint是元组列表的集合.
元组包含三个参数,
>方法名称(您的实际逻辑编码)
>验证消息(要向用户显示的消息)
>字段列表(要应用约束的字段)
如果条件在创建/更新记录上返回False,_constraint将引发验证消息.
只需添加约束,
def _check_date(self, cr, uid, vals, context=None):
for obj in self.browse(cr, uid, ids):
start_date = obj.start_date
end_date = obj.end_date
if start_date and end_date:
DATETIME_FORMAT = "%Y-%m-%d" ## Set your date format here
from_dt = datetime.datetime.strptime(start_date, DATETIME_FORMAT)
to_dt = datetime.datetime.strptime(end_date, DATETIME_FORMAT)
if to_dt < from_dt:
return False
return True
_constraints = [
(_check_date, 'Your Message!', ['start_date','end_date']),
]
在v8 api中,
@ api.constrains
这个装饰器将确保在创建,写入,取消链接操作时调用修饰函数.如果满足约束,则函数应该使用适当的消息引发openerp.exceptions.Warning.
@api.multi
@api.constrains('start_date','end_date')
def _check_date(self):
for obj in self:
start_date = obj.start_date
end_date = obj.end_date
if start_date and end_date:
DATETIME_FORMAT = "%Y-%m-%d" ## Set your date format here
from_dt = datetime.datetime.strptime(start_date, DATETIME_FORMAT)
to_dt = datetime.datetime.strptime(end_date, DATETIME_FORMAT)
if to_dt < from_dt:
#raise your exception
如果要更改现有约束,可以使用继承see here来完成
标签:python,python-2-7,odoo-8,openerp-7,openerp-8 来源: https://codeday.me/bug/20190623/1274917.html