How to remove a specific column value from SQLite Row Object in Python

Question:

So, I am fetching a record from a table in SQLite but I don’t want to include the first column which is "id" and primary key in the table.

But I can’t seem to achieve that. After fetching a row, I have the row data object. Is there any way, I can use the data from this object except for the first column. I actually, I want to pass this value to a template in flask but without the id.

import sqlite3

def get_db():
    conn = sqlite3.connect('leave_applications.db')
    conn.row_factory = sqlite3.Row
    return conn

def leave_applications():
    c = get_db().cursor()
    c.execute("SELECT * FROM leave_applications")
    data = c.fetchall()
    c.close()
    return data

data = leave_applications()

print(data[1:])

There are total 9 columns. If I try to print it after slicing, then it just says:

[<sqlite3.Row object at 0x7f2e68f5eb60>]
Asked By: Suleman Elahi

||

Answers:

As fetchall() returns a list of objects, trying to slice data returns a single sqlite3.Row object from that list.

Instead you want to slice every row in the list – i.e.:

data = leave_applications()
print([row[1:] for row in data])

Otherwise, if you only want the first/only row, use fetchone() instead, and then you can slice the single row that is in data instead.

Answered By: match
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.