0

This problem seems very simple, but I'm having trouble finding an already existing solution on StackOverflow.

When I run a sqlalchemy command like the following

valid_columns = db.session.query(CrmLabels).filter_by(user_id=client_id).first()

I get back a CrmLabels object that is not iterable. If I print this object, I get a list

[Convert Source, Convert Medium, Landing Page]

But this is not iterable. I would like to get exactly what I've shown above, except as a list of strings

['Convert Source', 'Convert Medium', 'Landing Page']

How can I run a query that will return this result?

5
  • I would not suggest this, but you can use eval but it should be avoided. Other than that I can not think of any other way. Commented Sep 15, 2020 at 7:49
  • Please edit the question to include the source of the CrmLabels class. Commented Sep 15, 2020 at 7:57
  • Probably you just want something like session.query(CrmLabels.name) Commented Sep 15, 2020 at 7:58
  • 1
    Please do not use eval. If you want to query the whole table, but as result tuples instead of mapped objects, use query(CrmLabels.__table__). But I think this seems a bit like an XY problem. Commented Sep 15, 2020 at 8:20
  • Thanks all. I ended up grabbing each value out of the table by using the class properties (example CrmLabels.status). It's not ideal, but it works and that's all I really need at the moment. Commented Sep 15, 2020 at 10:33

1 Answer 1

1

Below change should do it:

valid_columns = (
    db.session.query(CrmLabels).filter_by(user_id=client_id)
    .statement.execute()  # just add this
    .first()
)

However, you need to be certain about the order of columns, and you can use valid_columns.keys() to make sure the values are in the expected order.

Alternatively, you can create a dictionary using dict(valid_columns.items()).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.