Login

Retrieve similar objects from a model

Author:
henriklied
Posted:
June 15, 2007
Language:
Python
Version:
.96
Tags:
levenshtein similarity related
Score:
4 (after 4 ratings)

This function looks up items similar to a specific string. Requires the Levenshtein module.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from Levenshtein import ratio
from django.contrib.contenttypes.models import ContentType


def get_similar_items(mod, field, string, similarity_ratio=0.6, limit=None):
    """ 
        Get similar items for a specific model
        Example usage:
        similar = get_similar_items(Entry, 'title', 'Espresso is good for you', 0.5, 10)
        var = Entry.objects.filter(id__in=similar)
    """
    similar_list_id = []
    v = ContentType.objects.get_for_model(mod)
    c = v.model_class()
    for i in c.objects.all():
        if ratio(string, getattr(i,field)) > similarity_ratio:
            similar_list_id.append(i.id)
    return similar_list_id[:limit]

More like this

  1. truncate letters by trbs 8 years, 5 months ago
  2. Pledgie data parser by bram 7 years ago
  3. Generic Views for newforms by jnievas 7 years, 6 months ago
  4. Rails Style Controller by julan 6 years, 9 months ago
  5. Profiling middleware using cProfile by sgb 7 years, 4 months ago

Comments

Please login first before commenting.