我正在尝试通过系统描述,系统名称和系统标记中匹配单词数量的组合以及系统被其他人查看的次数来实现对结果进行排序的搜索用户(system_hits)。我正在尝试使用混合属性来执行此操作,但是我的实现出了问题,我不断收到错误“预期的SQL表达式对象或字符串,得到类型的对象”,任何洞察力为什么我收到这个错误?
@hybrid_method
def relevance(self,searchTag):
wordsInName = self.system_name.split() #turn string into list of strings
wordsInDescription = self.system_description.split()
wordsInTags = self.tags.split()
nameOccurrences = 0
descriptionOccurrences = 0
tagOccurrences = 0
for word in wordsInName:
if word == searchTag:
nameOccurrences += 1
for word in wordsInDescription:
if word == searchTag:
descriptionOccurrences += 1
for word in wordsInTags:
if word == searchTag:
tagOccurrences += 1
occurrenceRating = (nameOccurrences+descriptionOccurrences*.3+tagOccurrences*2)
return self.system_hits*occurrenceRating
@relevance.expression(cls,searchTag):
return self.system_hits
results = System.query.order_by(System.relevance)
正如你所看到的,在表达式部分我还没有弄清楚如何改进我的功能,我只是按命中次数排序。如果您对如何使用sqlalchemy编写上述函数有任何建议,这也会有所帮助,但这种担忧不那么直接。
答案 0 :(得分:0)
我决定让Python进行排序,这是我的最终实现:
wordsInName = self.system_name.split()
wordsInDescription = self.system_description.split()
wordsInTags = [tag.tag_name for tag in self.tags]
nameOccurrences = 0
descriptionOccurrences = 0
tagOccurrences = 0
for word in wordsInName:
if word == searchTag:
nameOccurrences += 1
for word in wordsInDescription:
if word == searchTag:
descriptionOccurrences += 1
for word in wordsInTags:
if word == searchTag:
tagOccurrences += 1
occurrenceRating = (nameOccurrences+descriptionOccurrences*.3+tagOccurrences*2)
return self.system_hits*occurrenceRating
注意:列表推导用于获取标记,因为系统和标记之间存在多对多关系。
results = System.query.all()
results.sort(key=lambda x: x.relevance(searchTag),reverse=True)