1

编码:

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)过滤它们虽然我对前者没有问题,但我有后面有问题。

4

1 回答 1

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'
于 2012-09-25T19:18:58.487 回答