0

使用以下函数,我试图确定一列是否已经具有 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

在这种情况下,也不会抛出任何消息。

我该如何解决?

4

2 回答 2

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 篇文章中) 。所以,问题一定出在循环上。但我真的需要从那个领域获得价值。

谢谢!

于 2013-09-20T09:13:00.870 回答
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
于 2013-09-20T10:07:48.740 回答