Pipsqweek Pipsqweek - 7 months ago 24
Javascript Question

Django "Similar Objects" Based on Similar Tag Sets

Lets say you have 1k objects, each of which have 10-50 tags.

For any given object, there must be a list of objects that have keywords in common with it from most to least.

Yet within Django parameters I know of no way to query in such a way.

Does such a thing exist in django or should I write an algorithm outside of django's constraints?




class Product(models.Model):

product_id = models.IntegerField(
unique=True,
)

slug = models.SlugField(
unique=True,
blank = True,
null = True,
)

meta_description = models.TextField(
max_length = 160,
blank = True,
null = True,
)


title = models.CharField(
max_length = 160,
blank = True,
null = True,
)


description = models.TextField(
blank = True,
null = True,
)

first_subject_heading = models.CharField(
max_length = 160,
blank = True,
null = True,
)

description_main = models.TextField(
blank = True,
null = True,
)

price = models.DecimalField(
max_digits=6,
decimal_places=2,
blank = True,
null = True,
)

published = models.DateTimeField(auto_now_add=True, blank=True)

tags = TaggableManager(
blank = True,
)

category = models.ManyToManyField(
'ProductCategory',
blank = True,
)

license_selection_model = models.IntegerField(
default = 1,
blank = True,
null = True,
)

minipic = models.ImageField(
upload_to='minipics/',
blank = True,
null = True,
)

def get_absolute_url(self):
from django.core.urlresolvers import reverse
return reverse('store.views.product', args=[self.slug])

def save(self, *args, **kwargs):
if not self.id and not self.slug:
#Only set the slug when the object is created.
self.slug = slugify(self.title) #Or whatever you want the slug to use
super(Product, self).save(*args, **kwargs)

def __str__(self):
return "%i, %s"%(self.product_id, self.title)


This is using postgres and the taggit extension (taggit's "similars" option has an error)

Answer

Django Taggit provides a TaggableManager to help in working with their API. It provides a similar_objects() method which returns a list of objects tagged similarly to a particular object in decreasing order of similarity.

From the docs:

similar_objects()
Returns a list (not a lazy QuerySet) of other objects tagged similarly to this one, ordered with most similar first. Each object in the list is decorated with a similar_tags attribute, the number of tags it shares with this object.

# returns list of objects tagged similarly
some_object.tags.similar_objects() 
Comments