[英]return the row only if exists in python
I want to return the values only if the particular row exist but I couldn't able to achieve it.Here, what I tried我只想在特定行存在但无法实现的情况下返回值。在这里,我尝试了什么
def CurrentRunning(UserId):
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivity] @UserId=%s', (UserId,))
result_set = cursor.fetchall()
data= []
data.append({
'TaskId':row[0],
'Value1':row[1],
'Value2' :row[2],
'SelectedTeam':0 if row[3] is exists else row[3],
'Level1':'0' if row[4] is exists else row[4],
'Level2':'0' if row[5] is exists else row[5],
'Level3':'0' if row[6] is exists else row[6],
'Level4':'0' if row[7] is exists else row[7],
'TotalVolume':'0' if row[8] is exists else row[8],
'ReturnDate':'0' if row[9] is exists else row[9],
})
print('Activity')
return Response(data)
You have to modify your if statement:您必须修改您的 if 语句:
def CurrentRunning(UserId):
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivity] @UserId=%s', (UserId,))
result_set = cursor.fetchall()
data= []
data.append({
'TaskId':row[0],
'Value1':row[1],
'Value2' :row[2],
'SelectedTeam': row[3] if row[3] is not None else '0',
'Level1': row[4] if row[4] is not None else '0',
'Level2': row[5] if row[5] is not None else '0',
'Level3': row[6] if row[6] is not None else '0'
...
...
and so on...等等...
The code编码
val = row[3] if row[3] is not None else '0'
result in val == '0' when row[3] is None, else val will be equal to row[3].当 row[3] 为 None 时导致 val == '0',否则 val 将等于 row[3]。
If you are not sure if row[3] exist (maybe because the index 3 is greater than len(row)) you can add extra checks:如果您不确定 row[3] 是否存在(可能是因为索引 3 大于 len(row)),您可以添加额外的检查:
val = row[3] if ((row is not None) and (len(row)>3) and (row[3] is not None)) else '0'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.