1

I want to select specific values from a table, by looking at the code from SQLAlchemy session.py

def query(self, *entities, **kwargs):
    """Return a new ``Query`` object corresponding to this ``Session``."""

    return self._query_cls(entities, self, **kwargs)

it does seem that as a function parameter, it accepts a tuple. So what I did was:

query = ('order', 'location')
columnsStr = 'order, location'
table = 'locations'
sql = "SELECT {0} FROM {1}".format(columnsStr, table)
data = session.query(query).from_statement(sql).all()

And it produces this error - InvalidRequestError: SQL expression, column, or mapped entity expected - got '('order', 'location')'

Why doesn't this work with a tuple?

P.S.

If I change the values of these:

query = 'location'
columnsStr = 'location'

I do get a result, but only for that single column.

1 Answer 1

3

Try

data = session.query('order', 'location').from_statement(sql).all()

alternately if you want to keep your tuple structure you can do something like this

data = session.query(*query).from_statement(sql).all()

the reason is when you pass in a tuple python then puts that tuple in a tuple

>>> x = (1,2,3)
>>> def f(*x):
    print x
>>> f(x)
((1, 2, 3),)
>>> f("location", "order")
('location', 'order')
>>> 
Sign up to request clarification or add additional context in comments.

1 Comment

That is absolutely right, thanks! I did finally catch that you do need to unpack your arguments tuple using *argumentsInTuple syntax from docs.python.org/2/tutorial/… but thanks a bunch for the answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.