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. FileField having auto upload_to path by junaidmgithub 1 month ago
  2. LazyPrimaryKeyRelatedField by LLyaudet 1 month, 1 week ago
  3. CacheInDictManager by LLyaudet 1 month, 1 week ago
  4. MYSQL Full Text Expression by Bidaya0 1 month, 1 week ago
  5. Custom model manager chaining (Python 3 re-write) by Spotted1270 1 month, 2 weeks ago

Comments

Please login first before commenting.