Is it possible to LEFT JOIN one QuerySet to another? I know it’s possible to INNER JOIN two, as follows:
QuerySet1.filter(foreign_key__in=QuerySet2)
Is there any way to achieve a similar effect but with a LEFT rather than INNER JOIN?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
That’s not an inner join. It’s a sub-select query, which gives you all the results of queryset1 which have their FK in queryset 2 – but it’s not a join, as at the end you only have the elements from the Q1 table, not those in q2.
The only way to do a real join – ie get elements from both tables in one query – is to use
select_related. What happens here is that the foreign key relationship in table1 are prepopulated with the result of the join. So, by default this is a left join, not an inner one, as you get the elements of table1 whether or not there are any matches in table2.You could combine the two techniques to simulate an inner join:
QuerySet1.select_related().filter(foreign_key__in=QuerySet2)but I’m not sure if the query creator is clever enough to combine those into a single join, or whether it will do a join + a subselect.