Task: I want to get all invoices where the project title matches a given string. The Invoice has a foreign key to Project.
The problem: I want to use a function for doing the project search so I can recycle and encapsulate this use-caes. To make this happen I have to use the __in operator instead of project__title__icontains=my_str. This will lead to an inefficient subquery. The later will create an efficient JOIN.
Code examples
I have two custom queryset methods. One lives in Project:
def search_title(self, title: str):
"""
Searches for projects having the given title or at least parts of it.
"""
return self.filter(title__icontains=title)
The second one lives in Invoice:
def search_project_title(self, project_title: str):
return self.filter(project__in=Project.objects.search_title(project_title))
Any ideas how I can tell the Django ORM that I prefer JOINs over Subqueries?
Thx!