2012-09-25 86 views
1

代碼:Django模型 - 兩個表過濾

class Article(models.Model): 
    hits    = models.IntegerField(help_text = 'Visits count') 
    answer_to_article = models.ForeignKey('self', blank = True, null = True) 
    slug    = models.SlugField(unique = True, help_text = 'Address') 
    meta_keywords  = models.CharField(max_length = 512) 
    title    = models.CharField(max_length = 256) 
    content   = models.TextField(verbose_name = 'Article contents', help_text = 'Article contents') 

    def get_similar_articles_from_meta_and_relation(self, phrase, offset = 0, limit = 10): 
     return ArticleToArticle.objects.find(article_one)[offset:limit] 

    class Meta: 
     db_table = 'article' 

#only a relational table - one article can have similar articles chosen by it's author 
class ArticleToArticle(models.Model): 
    article_one = models.ForeignKey(Article, related_name = 'article_source') 
    article_two = models.ForeignKey(Article, related_name = 'article_similar') 

    class Meta: 
     db_table = 'article_to_article' 

我的問題是有關從文章模型我get_similar_articles_from_meta_and_relation方法 - 我想: 1.找到連接到我的實例 2.過濾器的其他文章他們根據給定的短語(meta_keywords) 雖然我沒有前者的問題,但我確實對後者有問題。

+1

爲什麼定義自己的ArcticleToArcticle w當你可以使用https://docs.djangoproject.com/恩的/ dev/REF /模型/場/#django.db.models.ManyToManyField.symmetrical –

+0

感謝,該訣竅 –

回答

1

不知道什麼meta_keywords之間的關係螞蟻短語參數,但你可能想類似的東西:

class Article(models.Model): 
    hits    = models.IntegerField(help_text = 'Visits count') 
    answer_to_article = models.ForeignKey('self', blank = True, null = True) 
    slug    = models.SlugField(unique = True, help_text = 'Address') 
    meta_keywords  = models.CharField(max_length = 512) 
    title    = models.CharField(max_length = 256) 
    content   = models.TextField(verbose_name = 'Article contents', help_text = 'Article contents') 
    similar_articles = models.ManyToMany('self') 

    def get_similar_articles_from_meta_and_relation(self, phrase, offset = 0, limit = 10): 
     return self.similar_articles.filter(meta_keywords=phrase)[offset:limit] 

    class Meta: 
     db_table = 'article' 
+0

短語== meta_keywords,我只是把它命名爲嚴重;) –