SQLAlchemy:混合值对象,查询元组结果
我正在尝试按照文档中的示例,使用混合值对象来构建自定义比较器。
class CaseInsensitiveWord(Comparator):
"Hybrid value representing a lower case representation of a word."
def __init__(self, word):
if isinstance(word, basestring):
self.word = word.lower()
elif isinstance(word, CaseInsensitiveWord):
self.word = word.word
else:
self.word = func.lower(word)
def operate(self, op, other):
if not isinstance(other, CaseInsensitiveWord):
other = CaseInsensitiveWord(other)
return op(self.word, other.word)
def __clause_element__(self):
return self.word
def __str__(self):
return self.word
key = 'word'
"Label to apply to Query tuple results"
不过,我不明白为什么在类定义的最后加上了这个:
key = 'word'
"Label to apply to Query tuple results"
这个是用来干什么的呢?
1 个回答
4
虽然这不是一个完全成熟的Python特性,但有个惯例是对属性进行注释,方式和对函数和方法的注释一样,也就是在属性下面放一个字符串。像上面这样的注释会被一些工具,比如Sphinx,识别到。你可以在一些地方看到这些文档字符串生成的例子,比如http://www.sqlalchemy.org/docs/orm/mapper_config.html#sqlalchemy.orm.mapper.Mapper.class_manager。
补充一下:为什么它有一个实际的“.key”。当你说:
for row in session.query(MyClass.mycustomthing, MyClass.myothercustomthing):
print row.word, row.someotherword
“word”和“someotherword”这两个元组的键就是每个比较器上的“.key”的值。如果你在它上面调用label(),那会把它改成其他东西。我不确定它是否真的有必要存在。