2016-04-30 15 views
1

それぞれが10-50個のタグを持つ1kオブジェクトを持っているとしましょう。Django類似のタグセットに基づく類似のオブジェクト

任意のオブジェクトに対して、共通するキーワードを持つオブジェクトのリストが、ほとんどのものから最も少ないものまで存在する必要があります。

しかし、私はDjangoのパラメータの中で、私はこのような方法でクエリを行う方法がないことを知っています。

このようなことがdjangoに存在するのでしょうか、または私はdjangoの制約の外にアルゴリズムを書くべきですか?


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) 

これは

+0

対応するモデルを追加してください。 –

+0

タグが一致するようになりました...モデルが追加されました。 – Pipsqweek

+0

'some_object.tags.similar_objects()'は機能しますか? –

答えて

1

Django Taggitが彼らのAPIでの作業に役立つようにTaggableManagerを提供(taggitの "similars" オプションにエラーがある)はpostgresとtaggit拡張子を使用しています。 similar_objects()メソッドを提供します。このオブジェクトは、特定のオブジェクトと同様にタグ付けされたオブジェクトのリストを、類似性の高い順に返します。 docs:

similar_objects()
から

は、他の オブジェクトのlistQuerySet怠け者ではないが)最も類似最初に注文したこの1、と同様にタグ付けを返します。 リスト内の各オブジェクトはsimilar_tags属性で装飾され、 はこのオブジェクトと共有するタグの数です。