1

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!

1 Answer 1

0

In that case, you filter with:

def search_project_title(self, project_title: str):
    return self.filter(project__title__icontains=project_title)
Sign up to request clarification or add additional context in comments.

1 Comment

Thx for the input but as I said I want to use the function and NOT use the field of the fk-related model directly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.