我在 django 中使用带有 Model.objects.raw() 的查询语句“like %s%”时遇到问题。我猜问题出在“%”字符上,但我不知道它在哪里。这是我的模型的代码:
def listInRange(self, placeLat, placeLng, typeId, range, placeTag):
tags = ''
if placeTag:
tags = "AND (placeTag LIKE '%" + "%' OR placeTag LIKE '%".join(placeTag.split(',')) + "%')"
query = "SELECT *, \
( \
6371000 * \
acos( \
cos( radians(%s) ) * \
cos( radians(placeLat) ) * \
cos( radians(placeLng) - radians(%s) ) + \
sin( radians(%s) ) * \
sin( radians(placeLat) ) \
) \
) AS placeDistance, \
COUNT(r.reviewId) as placeReviews, \
(SUM(r.reviewPointPrice)/COUNT(r.reviewId)+SUM(r.reviewPointService)/COUNT(r.reviewId)+SUM(r.reviewPointLocation)/COUNT(r.reviewId)+SUM(r.reviewPointCondition)/COUNT(r.reviewId)+SUM(r.reviewPointComfort)/COUNT(r.reviewId))/5 AS averagePoint \
FROM place_place p \
LEFT JOIN review_review r \
ON r.reviewPlace_id = p.placeId\
WHERE placeType_id = %s %s \
GROUP BY p.placeId \
HAVING placeDistance < %s \
ORDER BY placeDistance"
return Place.objects.raw(query, [placeLat, placeLng, placeLat, typeId, tags, range])
如果 placeTag 不为空,则将其添加到 WHERE 条件中。当 placeTag 为空时没有这样的问题,但是当 placeTag 不为空时,我得到了这个错误:
Warning: Truncated incorrect DOUBLE value: '1AND (placeTag LIKE '%cafe%' OR placeTag LIKE '%pub%')'
使用带有“like”语句的 Model.objects.raw() 编写 sql 语句的更好方法是什么?