gpt4 book ai didi

python - 用于验证日期范围的 openERP 函数

转载 作者:太空狗 更新时间:2023-10-30 03:00:25 27 4
gpt4 key购买 nike

我的模块中有两个字段(开始日期和结束日期)。我想验证日期范围,因为 end_date 必须大于 start_date 并显示错误消息,如“结束日期应大于开始日期”,这是 mu 线。

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 支持两种类型的约束:SQLPython

SQL 约束被添加到数据库中的表定义中,并由 PostgreSQL 实现。它们是使用类属性 _sql_constraints 定义的。它是一个元组列表,其中包含约束标识符名称、约束的 SQL 以及要使用的错误消息。

Python 约束

在 v7 api 中,

_constraint 是元组列表的集合。

元组包含三个参数,

  1. 方法名称(您实际逻辑编码的地方)
  2. 验证消息(您要向用户显示的消息)
  3. 字段列表(您要对其应用约束的字段)
如果条件在创建/更新记录时返回 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 - 用于验证日期范围的 openERP 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29388329/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com