R0ck
R0ck

Reputation: 27

How to list table column to array in sqlalchemy

I am new to sqlalchemy and am trying to output a list of my columns to an array in python using flask.

Here is my table:

class DeviceTable(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(120), unique=True, nullable=False)
modes = db.Column(db.String(120), unique=False, nullable=False)
MN1 = db.Column(db.String(120), unique=False, nullable=True)
MN2 = db.Column(db.String(120), unique=False, nullable=True)
MN3 = db.Column(db.String(120), unique=False, nullable=True)
MN4 = db.Column(db.String(120), unique=False, nullable=True)
MN5 = db.Column(db.String(120), unique=False, nullable=True)
MN6 = db.Column(db.String(120), unique=False, nullable=True)
MN7 = db.Column(db.String(120), unique=False, nullable=True)
MN8 = db.Column(db.String(120), unique=False, nullable=True)
MN9 = db.Column(db.String(120), unique=False, nullable=True)
MN10 = db.Column(db.String(120), unique=False, nullable=True)
B1 = db.Column(db.String(120), unique=False, nullable=True)
B2 = db.Column(db.String(120), unique=False, nullable=True)
B3 = db.Column(db.String(120), unique=False, nullable=True)
B4 = db.Column(db.String(120), unique=False, nullable=True)
B5 = db.Column(db.String(120), unique=False, nullable=True)
B6 = db.Column(db.String(120), unique=False, nullable=True)
B7 = db.Column(db.String(120), unique=False, nullable=True)
B8 = db.Column(db.String(120), unique=False, nullable=True)
B9 = db.Column(db.String(120), unique=False, nullable=True)
B10 = db.Column(db.String(120), unique=False, nullable=True)

I want to output all of the 'name' objects to an array so I can use it to populate a listbox.

Upvotes: 1

Views: 4217

Answers (1)

Moses N. Njenga
Moses N. Njenga

Reputation: 771

This minimal sql-alchemy application tutorial will be helpful

I am assuming you have your app running without errors and having imported all relevant libraries. You can then query all the objects (an object contains all the attributes in your table), then iterate through the objects and append the name attribute of each to a list

device_names = [] # i initialize a list
all_devices = DeviceTable.query.all() #query all devices
for device in all_devices:
    device_names.append(device.name) #iterate through all the devices and add the name attribute to the list

Now the list device_names contains all device name in your table. On the link I have provided you will see how you can filter the results using any of the fields

I trust that is what you are looking for

Upvotes: 2

Related Questions