String to Column Type Conversion

413 views
Skip to first unread message

Tom Burdick

unread,
Nov 23, 2009, 11:33:18 AM11/23/09
to sqlalchemy
I would like to present my users a simple search box that searches a
table.

I have issues getting DataError when using the text input and trying
to do filter against a column that is an integer only column.

I want to have some code that takes a particular sqlalchemy column
object and attempts to convert a string to the column type so that it
can be used for filtering. Is there some way of doing this?

I tried something like... (key word is like here, I know it probably
isn't exactly correct)

myval = '10'
myval = mytable.c.some_id.type(myval)

I get an exception DataError.

I don't really understand how I could do what I want with pure
introspection like I do now.

-Tom

Tom Burdick

unread,
Nov 23, 2009, 12:05:56 PM11/23/09
to sqlalchemy
Ok, here's a small test. It actually works fine when using sqlite, but
not when using postgresql. I want it to work with postgresql!

This probably helps more than the description above.

http://www.pylonshq.com/pasties/fe6a2857f3f72d499914caabce0d41bc

-Tom

Conor

unread,
Nov 23, 2009, 1:42:03 PM11/23/09
to sqlal...@googlegroups.com
You can use sqlalchemy.cast() to coerce the type on the DB side:
coerced_teststr = cast(teststr, column.type)
records = session.query(History).filter(column==coerced_teststr)

-Conor

Thomas Burdick

unread,
Nov 23, 2009, 3:07:56 PM11/23/09
to sqlal...@googlegroups.com

This is exactly what I was looking for, thank you.

Tom

On Nov 23, 2009 12:42 PM, "Conor" <conor.edw...@gmail.com> wrote:

Tom Burdick wrote: > Ok, here's a small test. It actually works fine when using sqlite, but > not wh...

You can use sqlalchemy.cast() to coerce the type on the DB side:
coerced_teststr = cast(teststr, column.type)
records = session.query(History).filter(column==coerced_teststr)

-Conor

-- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. T...

Reply all
Reply to author
Forward
0 new messages