Login

Retrieve similar objects from a model

Author:
henriklied
Posted:
June 15, 2007
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 3 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 3 weeks ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.