-2

I'm trying to replace None with 0 but I'm getting an error as none type object has no attribute 'replace'. This is what I have tried

views.py:

def Activity(UserID):

        cursor = connection.cursor()
        cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,))
        result_set =cursor.fetchall()
        data = []
        for row in result_set:
         
            TaskId = row[0]
            data.append({
            'TaskId':row[0],           
            'TaskName' : row[1],
            'Source' : row[2],
            'Requester' : row[3].replace('None', '0') if row[3] == None else row[3] ,
            'type' : row[4],
            'IsActive':GetCurrentSubTaskSTatus(TaskId),
   
            })
        
            print(data)  
            return Response(data[0], status=status.HTTP_200_OK)
johnraj
  • 11
  • 1

2 Answers2

1
row[3].replace('None', '0') if row[3] == None else row[3]

Reflect about it:

if row[3] == None:
    row[3].replace('None', '0')

If row[3] is None, how can it be a string? And how can it contain 'None'?


You should replace that part with the following:

'0' if row[3] == None else row[3]

To better understand your problem, I would suggest you to read the following:

FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28
0

replace is a method for strings. None is not string, it is NoneType object.

You can try following code for your case:

'Requester' : row[3] or '0',

It will use value of row[3] if it is not None. Otherwise it will use '0'

pL3b
  • 1,155
  • 1
  • 3
  • 18
  • 1
    if you want to use ternary then try this:: 'Requester': row[3] if row[3] is not None else '0' – pL3b May 12 '22 at 13:34