Reputation: 423
I have some code that consists of 3 models, namely Course, Section and Lecture. A Course has many sections, a Section has many Lectures. Say i want to retrieve all the Lectures that belong to a particular Course, Course also has a property called 'title' so thats what will be used to filter. According to the tutorial i'm reading i should do this to get the lectures:
Lecture.objects.filter(section__course__title = "title of course)
This is pretty straightforward but what i'm wondering is how django is handling this under the hood. Some joins must be involved i can imagine, but according to the answer of this thread Does Django support JOIN? Django cannot make Joins. But when i look at the links he provides i can read that django does handle joins behind the scenes.
So lets assume django does handle joins, how does it know when to make a left join or a regular join? A regular join can only be made when it is certain that every parent model has a reference to a child model, the field is marked not null. If it can be null then a left join should be used. Is django intelligent enough to know when to make which join?
Thank you
Upvotes: 0
Views: 65
Reputation: 9395
The django ORM will be performing the join operations for you under the hood it abstracts away a lot of the complexity.
If you run the code below should will be able to see the SQL which django generates.
quseryset = Lecture.objects.filter(section__course__title = "title of course")
print(queryset.query)
It is explained in the django docs: Lookups that span relationships
Upvotes: 1