Django Model and Many-to-Many Relationships - Finding the Most Similar Objects

I am having a problem due to which I cannot find an explanation.

Given one object (in this case, “Article”), I want to use a different type of object (in this case, “Category”) to determine which other articles are most similar to Article X, how to measure the number of categories that they have in common . The relationship between the article and the category is Many-to-Many. A use case is to get a quick list of related objects for presentation as links.

I know exactly how I will write SQL manually:

select 
    ac.article_id
from 
    Article_Category ac
where
    ac.category_id in 
    (
        select
            category_id
        from
            Article_Category
        where
            article_id = 1  -- get all categories for article in question
    )
    and ac.article_id <> 1
group by 
    ac.article_id
order by 
    count(ac.category_id) desc, random() limit 5

, , , Django Model . . , . - ?

+4
1

, .

related_article_list = Article.objects.filter(category=self.category.all())\
                       .exclude(id=self.id)
related_article_ids = related_article_list.values('id')\
                      .annotate(count=models.Count('id'))\
                      .order_by('-count','?')

related_article_list , 2 , . , > 1, .

+2

Source: https://habr.com/ru/post/1540821/


All Articles