在Python中执行以下代码有什么问题? [英] What is wrong with following code in Python?

查看:91
本文介绍了在Python中执行以下代码有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对字段实施约束 但它不会引起约束验证,而是允许在不显示任何约束消息的情况下保存记录

I was trying to implement a constraint for a field but instead of causing a constraint validation, it allows the record to get saved without showing any constraint message

def _check_contact_number(self, cr, uid, ids, context=None):
    for rec in self.browse(cr, uid, ids, context=context):
                if rec.contact_number:
                    size=len(str(rec.contact_number))
                    if size<10:
                       return False
            if not contact_number:
            return {}
            contact_number = rec.contact_number.replace('.','') 
#removes any '.' from the string
            contact_number = rec.contact_number.replace(' ','') 
#removes space from the string
            if not  contact_number.isdigit():
            return False
        return {}

    _constraints = [
        (_check_contact_number, 'Enter valid phone number...!', 
['contact_number']),
      ]

请问有人纠正我.非常感谢

Kindly anyone correct me. Thank you very much

推荐答案

其他答案听起来很合理,这是我尝试使用新的Odoo ORM API:

Some of the other answers sound reasonable, here is my attempt using the new Odoo ORM API:

@api.one
@api.constrains('contact_number')
def _check_contact_number(self):
    contact_number = self.contact_number.replace('.','').replace(' ','')
    if len(contact_number) < 10:
        raise exceptions.ValidationError(
            "Phone number has to contain at least 10 digits!"
        )
    if not contact_number.isdigit():
        raise exceptions.ValidationError(
            "Phone number can only contain digits, spaces and dots!"
        )

用于定义约束的当前API 好多了.您应该真正学习它.您正在使用的旧API已被弃用,最终将被删除.

The current API for defining constrains is much nicer. You should really learn it. The old API you are using is deprecated and will eventually be removed.

Atul Arvind关于记住重新启动服务器并升级特定模块的提示也非常重要.

Atul Arvind's tip about remembering to restart server and upgrade the particular module is also very important.

这篇关于在Python中执行以下代码有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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