Get models ordered by an attribute that belongs to its OneToOne model
<p>Let's say there is one model named <code>User</code> and the other named <code>Pet</code> which has a <code>OneToOne</code> relationship with <code>User</code>, the <code>Pet</code> model has an attribute <code>age</code>, how to get the ten <code>User</code> that owns the top ten <code>oldest</code> dog?</p>

<pre><code>class User(models.Model):
     name = models.CharField(max_length=50, null=False, blank=False)

class Pet(models.Model):
     name = models.CharField(max_length=50, null=False, blank=False)
     owner = models.OneToOneField(User, on_delete=models.CASCADE)
     age = models.IntegerField(null=False)
</code></pre>

<hr>

<p>In <code>User</code>, there is an attribute <code>friends</code> that has a <code>ManyToMany</code> relationship with <code>User</code>, how to get the ten <code>friends</code> of <code>User Tom</code> that owns the top ten <code>oldest</code> dog?</p>

<pre><code>class User(models.Model):
     name = models.CharField(max_length=50, null=False, blank=False)
     friends = models.ManyToManyField(self, ...)

class Pet(models.Model):
     name = models.CharField(max_length=50, null=False, blank=False)
     owner = models.OneToOneField(User, on_delete=models.CASCADE)
     age = models.IntegerField(null=False)
</code></pre>

<p>Use the double-underscore syntax.</p>

<pre><code>User.objects.order_by('-pet__age')[:10]
</code></pre>

<p><strong>Edit</strong></p>

<p>To get the ten friends of Tom, you can get the instance and filter:</p>

<pre><code>User.objects.get(name='Tom').friends.order_by('-pet__age')[:10]
</code></pre>

<p>or if you already have Tom:</p>

<pre><code>tom.friends.order_by('-pet__age')[:10]
</code></pre>

python django python-3.x