Priyan RockZ
Priyan RockZ

Reputation: 1615

How to Null check in Postgre fresh table?

now my error is like this

  File "/home/bellvantage/Documents/openerp-7.0/openerp-7/openerp/addons/bpl/bpl.py", line 119, in _max_reg_no
    res = cr.fetchone()[0]
TypeError: 'NoneType' object has no attribute '__getitem__'

I have a table called bpl_worker.there is a function i called in my python code.

def _max_reg_no(self, cr, uid, context=None):
    res = {}
    cr.execute("""
    select COALESCE(register_no, 'W00001') as reg_no        
    from bpl_worker 
    where id in 
    (select coalesce(max(id),0) from bpl_worker)        
    """)
    rows = cr.fetchall()
    if len(rows) == 0:
        return 'W00001'
    else:
        res = rows[0]
        emp_no = str(res)
        emp_int = emp_no[1:6]
        emp_no_int = int(emp_int)
        result = 'W' + (str(emp_no_int + 1).zfill(4))
        return result        

if table have at least one record then its worked and return records.in inital level can't get records of the if null message as output. please help me to sort this issue

thanks

now my table if null issue ok.but after my record return as 'W00001' then error comes at below point

res = cr.fetchone()[0]

Upvotes: 0

Views: 372

Answers (1)

hegemon
hegemon

Reputation: 6764

First, the whole section:

CASE 
WHEN register_no IS NULL 
    THEN 'Empty' 
ELSE register_no 
    END

can be replaced with:

COALESCE(register_no, 'Empty')

Coalesce is a well known function to handle null values in rows. There is also an IFNULL function which serves same needs.

As far as I get your question, you would like to fetch records from an empty table (i.e. table containing no rows). This can't work. You may want to check for the number of records returned by the query first, this can be don either by examining cr.rowcount attribute, or by trying to fetch all rows and the inspecting the length of the resulting array:

rows = cr.fetchall()
if len(rows) == 0: return 'Empty'

Upvotes: 1

Related Questions