martinqt
martinqt

Reputation: 719

SQLAlchemy filter always returns false

I have a simple player entity:

__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 the 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 query, the result is None. I have tried with filter_by() and get the same result.

Any help is welcome.

Upvotes: 5

Views: 1592

Answers (2)

Eevee
Eevee

Reputation: 48536

While using @hybrid_property will fix this in the general case, you shouldn't need to be decoding manually at all. Just set the column type to Unicode instead of String and, assuming your server plays nice, you should correctly get back a unicode.

You also don't need the id property at all.

So all you should need for this class is:

class Player(Base):
    __tablename__ = 'player'

    id = Column(SmallInteger, primary_key=True)
    nickName = Column(Unicode)

(Both the column names and __init__ arguments can be generated automatically.)

If there's some reason your database isn't handling Unicode correctly, well, that's a different problem that we'd love to help you fix. :)

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121216

You cannot use regular @propertys as query parameters. Use a @hybrid_property instead:

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 on the attribute on the class) useful in SQL expressions.

Upvotes: 2

Related Questions