Marek M.
Marek M.

Reputation: 3951

Django models - two tables filter

The code:

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'

My question is about my get_similar_articles_from_meta_and_relation method from Article model - I'd like to: 1. find other articles connected to my instance 2. filter them according to given phrase (meta_keywords) While I don't have problem with the former, I do have a problem with the later.

Upvotes: 1

Views: 88

Answers (1)

Ioan Alexandru Cucu
Ioan Alexandru Cucu

Reputation: 12269

Not sure what the relation between meta_keywords ant the phrase parameter is, but you probably want something similar to:

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'

Upvotes: 1

Related Questions