简体   繁体   English

SQLAlchemy过滤器始终返回false

[英]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: 我打印players var我得到了这个:

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 . 显然,当我在会话查询结束时添加.first()时,结果为None I have tried with filter_by() and get the same result. 我尝试过filter_by()并获得相同的结果。

Any help is welcome. 欢迎任何帮助。

You cannot use regular @property s as query parameters. 您不能将常规@property用作查询参数。 Use a @hybrid_property 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 on the attribute on the class) useful in SQL expressions. 这使得Player.nickName (在类的属性上也是如此)在SQL表达式中很有用。

While using @hybrid_property will fix this in the general case, you shouldn't need to be decoding manually at all. 虽然使用@hybrid_property 在一般情况下修复此问题,但您根本不需要手动解码。 Just set the column type to Unicode instead of String and, assuming your server plays nice, you should correctly get back a unicode . 只需将列类型设置为Unicode而不是String ,并假设您的服务器运行良好,您应该正确地返回一个unicode

You also don't need the id property at all. 您根本不需要id属性。

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.) (列名和__init__参数都可以自动生成。)

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. 如果您的数据库没有正确处理Unicode,那么这就是我们希望帮助您解决的另一个问题。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM