Django multiple one to many join
<p>I have one to many relationship in many places in my Django app.
For example I have user, home and key:</p>

<pre><code>class User(Model):
    id_user = models.AutoField(primary_key=True)
class Home(Model):
    id_home = models.AutoField(primary_key=True)
    id_user = models.ForeignKey('user.User', models.DO_NOTHING, db_column='id_user_home')
class Key(Model):
    id_key = models.AutoField(primary=True)
    id_home = models.ForeignKey('home.Home', models.DO_NOTHING, db_column='id_home_key')
</code></pre>

<p>From session I have <code>user = User(1)</code> and I want to get all keys for homes of this user.</p>

<p>What you are looking for is <code>Key.objects.filter(id_home__id_user=user)</code>. This creates 2 joins such that <code>Key x Home x User</code> and filters on <code>id_user</code>.</p>

<p>You can inspect generated sql with:</p>

<p><code>print(Key.objects.filter(id_home__id_user=user).query)
</code></p>

python django join