Django型号双表fi

2024-04-20 10:14:44 发布

您现在位置:Python中文网/ 问答频道 /正文

代码:

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'

我的问题是关于如何从文章模型中获取相似的文章和关系方法-我想: 1查找与我的实例相关的其他文章 2根据给定的短语(meta\u关键字)过滤它们 我对前者没有意见,但对后者有意见。你知道吗


Tags: textnametruemodelmodelsarticle文章table
1条回答
网友
1楼 · 发布于 2024-04-20 10:14:44

不确定meta_关键字和短语参数之间的关系,但您可能希望类似于:

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'

相关问题 更多 >