Get .similar_features() working right.

This commit is contained in:
Schuyler Erle 2011-08-28 09:55:00 +02:00
parent 960eb21283
commit 863c49575f

View File

@ -73,22 +73,23 @@ class Feature(models.Model):
cursor = connection.cursor() cursor = connection.cursor()
name = unicode(self).replace("'", "''") # escape ' name = unicode(self).replace("'", "''") # escape '
cursor.execute(""" cursor.execute("""
SELECT *, %f * similarity / distance AS score FROM ( SELECT *, %f * similarity / (distance + 1.0) AS score FROM (
SELECT url, preferred_name, feature_type, SELECT id, url, preferred_name, feature_type_id,
admin1, admin2, is_primary, admin1, admin2, is_primary,
similarity(preferred_name, '%s') AS similarity, similarity(preferred_name, '%s') AS similarity,
st_distance_sphere(geometry, '%s') AS distance st_distance_sphere(geometry, 'SRID=4326;%s') AS distance
FROM places_feature FROM places_feature
WHERE geometry && st_buffer('%s', %f) WHERE geometry && st_buffer('%s', %f)
AND preferred_name % '%s' AND preferred_name %%%% '%s'
AND id <> %d
) AS whatever ) AS whatever
WHERE %f * similarity / distance >= 1.0 WHERE %f * similarity / (distance + 1.0) >= 1.0
ORDER BY similarity / distance DESC""" ORDER BY similarity / (distance + 1.0) DESC"""
% (scale_factor, name, self.geometry.wkt, self.geometry.wkt, % (scale_factor, name, self.geometry.wkt, self.geometry.wkt,
max_distance*0.00001, name, scale_factor) max_distance*0.00001, name, self.id, scale_factor)
) )
result_list = [] result_list = []
fields = ('url', 'preferred_name', 'feature_type', 'admin1', 'admin2', 'is_primary') fields = ('id', 'url', 'preferred_name', 'feature_type_id', 'admin1', 'admin2', 'is_primary')
for row in cursor.fetchall(): for row in cursor.fetchall():
vals = dict(zip(fields, row[:len(fields)])) vals = dict(zip(fields, row[:len(fields)]))
p = type(self)(**vals) p = type(self)(**vals)