SQLAlchemy filter always returns false
I have a simple object:
__tablename__ = 'player'
_id = Column('id', SmallInteger, primary_key=True)
_nickName = Column('nick_name', String)
def __init__(self, nickName):
self._nickName = nickName
@property
def id(self):
return self._id
@property
def nickName(self):
return self._nickName.decode(encoding='UTF-8')
@nickName.setter
def nickName(self, nickName):
self._nickName = nickName
when i do:
players = session.query(Player).filter(Player.nickName=='foo')
and i print players
var i got this:
SELECT player.id AS player_id, player.nick_name AS player_nick_name
FROM player
WHERE false
Obviously, when I add .first()
at the end of the session request, the result is None
. I tried with filter_by()
and got the same result.
Any help is appreciated.
source to share
When used, it @hybrid_property
will be fixed in general, you don't need to decode manually at all. Just set the column to type Unicode
instead String
and if your server plays well you should return it correctly Unicode
.
You don't need a property either id
.
So, all you need for this class:
class Player(Base):
__tablename__ = 'player'
id = Column(SmallInteger, primary_key=True)
nickName = Column(Unicode)
(Column names and arguments __init__
can be generated automatically.)
If there is any reason why your database is not handling Unicode correctly, well, this is another problem that we would like to help you fix. :)
source to share
You cannot use regular ones @property
as query parameters. Use instead @hybrid_property
:
from sqlalchemy.ext.hybrid import hybrid_property
@hybrid_property
def nickName(self):
return self._nickName.decode(encoding='UTF-8')
@nickName.setter
def nickName(self, nickName):
self._nickName = nickName
This makes Player.nickName
(so the class attribute) useful in SQL expressions.
source to share