使用以下函数,我试图确定列是否已经有X值。
def error_verify(self, cr, uid, ids, context=None):
for record in self.browse(cr, uid, ids, context):
nr = int(record.nr_service) # Gets the current value from field
cr.execute("SELECT nr_service FROM services WHERE nr_service = %s", [nr])
values = cr.fetchall()
if values: # if there's ANY result it means there's at least one
# row with that value in the table
return True
return False
以这种方式调用该函数:
_constraints = [
(error_verify, 'Error: Already that ID in the table', [''])
]
事情是:我没有得到任何结果。我正在尝试收到错误消息,但我无法到达那里。我将一些现有值放在“record.nr_service”中,但它不会抛出任何消息。我的问题是:我的功能是否合适?
我也尝试过这种方式:
def error_verify(self, cr, uid, ids, context=None):
for record in self.browse(cr, uid, ids, context):
nr = int(record.nr_service) # Gets the current value from field
cr.execute("SELECT nr_service FROM services WHERE nr_service = %s", [nr])
values = cr.fetchall()
for n in values:
if nr == int(n[0]):
return True
return False
在这种情况下,也不会抛出任何信息。
我该如何解决?
答案 0 :(得分:0)
好的,我一直在测试,我想我发现了我的错误。假设我在数据库中有值“3”。因此,每当我在字段中写入值“3”时,它应该显示错误消息,否则它会让我自由。
这有效:
def error_verify(self, cr, uid, ids, context=None):
cr.execute("SELECT nr_service FROM services WHERE nr_service = %s", (3,))
values = cr.fetchall()
if values:
return False # Returning false means that there's already a value "3" in the database.
return True
这也有效:
def error_verify(self, cr, uid, ids, context=None):
cr.execute("SELECT nr_service FROM services WHERE nr_service = %s", (55,))
values = cr.fetchall()
if values:
return False
return True # it returns true, it let me go free, because I don't have any value of "55" in the database
这里的问题是我无法在查询中告诉值“3”,我应该从字段中获取该值 - > OpenERP字段 - >像这样:
for record in self.browse(cr, uid, ids, context=context): # loop through the fields
nr_value = record.nr_service # this is the field
cr.execute("SELECT nr_service FROM services WHERE nr_service = %s", (nr_value,))
values = cr.fetchall()
if values:
return False
return True
使用此代码,它会检索错误消息(在第1篇文章中),无论我在字段中放置的值。所以,问题必须在循环上。但我真的需要从那个领域获得价值。
谢谢!
答案 1 :(得分:0)
解决。
def verify_service(self, cr, uid, ids, context=None):
record = self.browse(cr, uid, ids)[0]
rec_value = str(record.nr_service)
cr.execute("SELECT COUNT(*) FROM services WHERE nr_service = %s", [rec_value])
values = cr.fetchone()
if values[0] <= 1:
return True
return False