2

Suppose I have created a table via SQLAlchemy's declarative system.

class Recipe (Base):
    __tablename__ = 'recipe'

    id = Column(Integer, primary_key=True)
    title = Column(Text)
    instructions = Column(Text)

Let's now assume I perform a query which yields an instance r of the Recipe class. How can I get r's nth column value? (e.g. express r.instructions as something like r[2] -- which doesn't work.)

Bernhard Reiter
  • 771
  • 7
  • 20
  • What determines the order of the columns? – Mark Hildreth Mar 20 '14 at 17:36
  • I thought I did by the order I was specifying the class members. Isn't that the case? – Bernhard Reiter Mar 20 '14 at 20:25
  • The way the question is worded, we could only assume that that was the case. So, since that is what you're looking for, check out [this question](http://stackoverflow.com/questions/4459531/how-to-read-class-attributes-in-the-same-order-as-declared). – Mark Hildreth Mar 20 '14 at 21:06
  • I hoped my example would make that clear, but I see that it was by no means nonambiguous. Anyway, thanks for the link; though that workaround specified there is a bit more complex than I hoped I needed. Isn't there anything SQLAlchemy specific that I can use to make it simpler? – Bernhard Reiter Mar 20 '14 at 21:28

1 Answers1

5

Found something:

getattr(r, list(Recipe.__table__._columns)[n].name)

Recipe.__table__columns returns what looks like a list but is actually an ImmutableColumnCollection. So we use list to turn it into one, and take that list's nth element's name -- the column name (so for n == 2, that would be instructions). Finally, we getattr the attribute of that name from our Recipe object, r.

Bernhard Reiter
  • 771
  • 7
  • 20