How to cross two ManyToMany fields with Django Query?

Let's say I have the following Django models:

class A(models.Model): keywords = models.ManyToManyField(Keyword) class B(models.Model): keywords = models.ManyToManyField(Keyword) 

I have an object A. I want to find all objects B where some keyword in object B matches the keyword in object A.

What is the correct way to write this query?

+4
source share
2 answers

For my sanity, I replace A and B with an article and a blog, respectively. This simplifies the analysis of related names. So we have:

 class Article(models.Model): keywords = models.ManyToManyField(Keyword) class Blog(models.Model): keywords = models.ManyToManyField(Keyword) 

This should work in a single query:

 article = Article.objects.all()[0] Blog.objects.filter(keywords__in=Keyword.objects.filter(articles=article)) 

Django will combine Keyword.objects.filter into a Blog.objects.filter query, making only one database call.

+7
source

If a is an instance of a , something like this:

 B.objects.filter(keywords__pk__in=a.keywords.values_list('pk', flat=True)) 
0
source

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


All Articles